【发布时间】:2019-02-05 17:47:33
【问题描述】:
我是使用 excel VBA 解析 HTML 数据的新手。下面是我的代码和一些示例 HTML。 HTML 中的注意事项:pt-DefaultParagraphFont-000016">oles and Responsibilities
我想打开数百个类似的内部网页,然后找到 Roles and Responsibilities 部分,然后开始抓取某些数据并将其粘贴到各个列中。
我在下面修改了我的代码,它现在可以根据推荐的内容运行。
顺便说一句,以防万一这对其他人有所帮助,我确实发现了一个很好的解决方案,可以解决“调用的对象已断开连接”错误;这是解决方法:设置 ie = New InternetExplorerMedium
Option Explicit
Enum READYSTATE
READYSTATE_UNINITIALIZED = 0
READYSTATE_LOADING = 1
READYSTATE_LOADED = 2
READYSTATE_INTERACTIVE = 3
READYSTATE_COMPLETE = 4
End Enum
Sub ImportStackOverflowData()
Dim a As String
Dim i As Long
Dim ie As InternetExplorer
Dim html As HTMLDocument
'Set ie = New InternetExplorer 'replaced with InternetExplorerMedium to fix error
Set ie = New InternetExplorerMedium 'this fixes this error: The object invoked has disconnected from its client
ie.Visible = False
ie.navigate "policy.myurl.com"
Do While ie.READYSTATE <> READYSTATE_COMPLETE
DoEvents
Loop
Set html = ie.document
Dim tag As IHTMLElement
Dim tags As IHTMLElementCollection
Set tags = html.getElementsByClassName("pt-000015")
For Each tag In tags
'more logic here
Next
Set html = ie.document
Set ie = Nothing
End Sub
HTML 示例:
div class="pt-000015">
数据治理是一项共同责任。
【问题讨论】:
-
pt-000015是类元素,不是id? -
你可以试试
.getElementsByClassName- 而不是getElementById。 -
这不是 XML,而是 HTML。问题标题具有误导性。
标签: html excel vba web-scraping screen-scraping