html - 从 iframe 中按 ID 获取元素

标签 html excel vba getelementbyid

我正在尝试将股价的最新价格复制到 Excel 工作表中

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

Internet Explorer 打开并导航到该网站,但最后的价格没有复制到我的工作表中。我添加了 Debug.Print element.innertext 但没有出现在直接 Pane 中。

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

最佳答案

所以问题是最后价格值元素包含在 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

另外,Yahoo 有非常简单的 VBA 接口(interface)来拉动股票价格,所以除非你需要 Morningstar 因为你拉动了不知名的共同基金或私有(private)基金的价格,我会说你可以通过切换到 Yahoo 源来让自己更容易..

希望对您有所帮助, 丝绸密码

关于html - 从 iframe 中按 ID 获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41917779/

相关文章:

javascript - 表单提交到 _blank 后如何刷新表单页面?

excel - 将行号作为 Excel 工作表中的变量传递

vba - 在excel vba中为前10行填写1,0

excel - 通过 VBA Excel 进行 Plink SSH 访问并终止 cmd 提示符

html - 我怎样才能居中 flex-wrap 行,同时保持 flex 元素左对齐?

html - 奇怪的导航问题 - 只有一个元素不工作

Excel:使用特殊单元格格式对特定数字进行数据验证

vba - Outlook VBA Mailitem 属性 SenderEmailAddress 未正确返回地址

VBA 类。调用具有多个参数和静态函数的方法

javascript - 在容器内显示的 CSS 幻灯片。如何?