【问题标题】:Extracting data from website using VBA使用VBA从网站中提取数据
【发布时间】:2020-07-13 23:30:56
【问题描述】:

我想提取可以在网站上找到的项目的项目状态。有关如何解析 html 的示例,请参见下文。我想提取文本 Start,它是 td 和 /td 之间的文本。请参阅下面的 html 我的代码。

 <div id="ProjectStatus">
 <tr>
 <th>
 <span id="ProjectStatus_Label1" title="De status van het project">Projectstatus</span>
 </th>
 <td>Start</td>
 </tr>

您将在下面找到我目前拥有的代码。这段代码只给了我字符串“Projectstatus”,这不是我想要的。如何提取“开始”这个词?

Private Sub btnClick()

Dim ieApp As InternetExplorer
Set ieApp = New InternetExplorer
Set ieApp = CreateObject("internetexplorer.application")

With ieApp
 .Navigate "url"
 .Visible = True
End With

Do While ieApp.Busy
    DoEvents
Loop 

Set getStatus = ieApp.Document.getElementById("ProjectStatus_Label1")

strStatus = getStatus.innerText

MsgBox (strStatus) 'gives met the text "Projectstatus, but I need the text "Start"

ieApp.Quit
Set ieApp = Nothing

End Sub

【问题讨论】:

    标签: html ms-access vba


    【解决方案1】:

    ProjectStatus_Label1 开始,实现这一点需要一些 DOM 导航。

    使用以下内容:

    Do While ieApp.Busy
        DoEvents
    Loop
    Set labelSpan = ieApp.Document.getElementById("ProjectStatus_Label1")
    Set tableHeader = labelSpan.Parent
    Set tableRow = tableHeader.Parent
    For Each child In tableRow.Children
        If child.tagName = "TD" 'This is the element you're looking for
             Debug.Print child.innerText
             Exit For
        End If
    Next
    

    当然,我强烈建议您修改此代码并使用显式声明和Option Explicit,但您的问题中没有,所以我不会回答。

    此外,我使用了一些分配(labelSpan、tableHeader)来进行演示。您可以使用 Set tableRow = ieApp.Document.getElementById("ProjectStatus_Label1").Parent.Parent 并删除其他声明。

    或者您可以使用代码高尔夫,更难理解的方法,从 ProjectStatus div 开始:

    Debug.Print ieApp.Document.getElementById("ProjectStatus").GetElementsByTagName("td")(0).innerText
    

    【讨论】:

    • 您好 Erik,您提供的代码有效。我不得不将 .Parent 更改为 .ParentElement。谢谢!
    • 这有点奇怪。我们必须使用不同版本的 IE(我使用的是 IE11,并使用带有后期绑定的 ShDocVw.InternetExplorer 而不是 CreateObject)。对我来说当然是.Parent。 IE自动化的文档很少,版本不兼容很多,所以主要是反复试验。很高兴它成功了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    相关资源
    最近更新 更多