Excel VBA按ID获取元素

问题描述 投票:3回答:1

我正在尝试将股票价格的最后价格复制到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
html excel vba excel-vba getelementbyid
1个回答
0
投票

所以问题是最终价格元素包含在iFrame-iFrames中有点痛苦,需要特殊的语法和一些额外的步骤来检索他们的数据 - 基本上你想要找到iFrame,得到它的HTML使用.ContentDocument,然后可以像通常那样使用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界面来拉动股票价格,所以除非你需要晨星,因为你在晦涩的共同基金或私募基金上提价,我会说你可以通过切换到雅虎来源让自己变得更容易。

希望这会有所帮助,TheSilkCode

© www.soinside.com 2019 - 2024. All rights reserved.