【问题标题】:Get Element by ID from inside an iframe从 iframe 中按 ID 获取元素
【发布时间】:2017-06-14 12:58:01
【问题描述】:

我正在尝试将股价的最新价格从

复制到 Excel 工作表中

<div id="last-price-value" vkey="LastPrice">127.36</div>.

Internet Explorer 打开并导航到该站点,但最后一个价格没有复制到我的工作表中。我添加了Debug.Printelement.innertext,但立即窗格中没有出现任何内容。

Dim element As IHTMLElement
Dim elements As IHTMLElementCollection

Dim ie As New InternetExplorer
Dim html As HTMLDocument

my_page = "http://www.morningstar.com/stocks/XASX/COH/quote.html"

With ie
    .Visible = TRUE
    .Navigate my_page

    Do While ie.readyState <> READYSTATE_COMPLETE
    Loop

    Set html = ie.document
    Set element = html.getElementById("last-price-value")    
    Debug.Print element.innertext

    Sheets("Sheet 1").Range("A2").Value = element.innertext     
End With

【问题讨论】:

  • 在您的代码指向的页面中,没有 ID 设置为 last-price-value 的元素。可以通过网页浏览器打开页面查看,打开网页工具,进入控制台执行document.getElementByID('last-price-value'),会返回null。所以问题出在你的选择器上,而不是你的代码上。
  • 谢谢。我正在尝试复制此元素的内部文本:
    127.36
    。这是否意味着我需要将代码更改为 getElementsByCaseName()?谢谢
  • 您的问题是元素在 iframe 内。不能直接引用,首先得拿到iframe的文档,然后才能继续。现在,我不知道该怎么做,但应该没那么难,你可以开始here

标签: html excel vba getelementbyid


【解决方案1】:

所以问题是最后一个价格值元素包含在 iFrame 中 - iFrame 有点麻烦,需要特殊的语法和一些额外的步骤来检索它们的数据 - 基本上你想找到 iFrame , 使用.ContentDocument 获取其 HTML,然后可以像往常一样使用该 HTML 文档...但是,这种从 iFrame 中提取数据的情况特别痛苦,因为主网页位于 iFrame 所在的一个域中在另一个域上,阻止您从主页访问 iFrame 的 HTML...所以,您必须做的是: 1-加载主页 2-找到框架 3- 获取框架的 URL 4- 加载框架 URL 5- 拉出最后的价格值..

参见下面的代码示例:

Public Sub sampleCode()
Dim IE As New InternetExplorer
Dim HTMLDoc As HTMLDocument
Dim parentURL As String
Dim frames As IHTMLElementCollection
Dim frameURL As String
Dim frameHTML As HTMLDocument
Dim fCounter As Long
Dim targetElement As HTMLObjectElement

parentURL = "http://www.morningstar.com/stocks/XASX/COH/quote.html"
'1- Load the main page
With IE
   .Visible = False
   .Navigate parentURL
    While .Busy Or .readyState <> READYSTATE_COMPLETE: Wend
    Set HTMLDoc = IE.document
End With

'2- Find the frame
Set frames = HTMLDoc.getElementsByTagName("iframe")
'Loop through all the frames
For fCounter = 0 To frames.Length - 1
    'Test each frame's ID to find the correct one (numerical appendix to ID can change so need to test for pre-fix)
    If Left(frames(fCounter).ID, 10) = "QT_IFRAME_" Then
        '3- Get the frame's URL
        frameURL = frames(fCounter).src
        Exit For
    End If
Next

'4- Load the frame URL
With IE
   .Navigate frameURL
    While .Busy Or .readyState <> READYSTATE_COMPLETE: Wend
    Set frameHTML = IE.document
End With

'Find and pull the last price
Set targetElement = frameHTML.getElementById("last-price-value")
Sheets("Sheet 1").Range("A2").Value = CDbl(targetElement.innerText)

IE.Quit
Set IE = Nothing
End Sub

此外,雅虎有非常简单的 VBA 界面来拉股票价格,所以除非你需要晨星,因为你正在为不起眼的共同基金或私人基金拉价格,我会说你可以通过切换到雅虎资源来让自己更轻松..

希望这会有所帮助, 丝绸代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-08
    • 2010-12-11
    • 1970-01-01
    • 2011-03-25
    • 2020-10-12
    • 1970-01-01
    相关资源
    最近更新 更多