Excel VBA按ID获取元素

时间:2017-01-29 05:01:51

标签: html excel vba excel-vba getelementbyid

我试图将最后一次股票价格复制到Excel工作表中。 Internet Explorer打开并导航到该站点,但最后一个价格未复制到我的工作表。我添加了Debug.Print element.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

1 个答案:

答案 0 :(得分:0)

所以问题是最终价格元素包含在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界面来拉动股票价格,所以除非你需要晨星,因为你在晦涩的共同基金或私募基金上提价,我会说你可以通过切换到雅虎来源让自己变得更容易。 / p>

希望这有帮助, TheSilkCode