【发布时间】:2019-06-10 05:12:12
【问题描述】:
我正在尝试从 Wikipedia 页面中选取“关键人物”字段:https://en.wikipedia.org/wiki/Abbott_Laboratories 并将该值复制到我的 Excel 电子表格中。
我设法使用 xml http 来做到这一点,这是我喜欢它的速度的一种方法,你可以看到下面的代码正在运行。
但是代码不够灵活,因为 wiki 页面的结构可能会发生变化,例如它在此页面上不起作用:https://en.wikipedia.org/wiki/3M
由于tr td结构不完全相同(关键人物不再是3M页面的第8个TR)
如何改进我的代码?
Public Sub parsehtml()
Dim http As Object, html As New HTMLDocument, topics As Object, titleElem As Object, detailsElem As Object, topic As HTMLHtmlElement
Dim i As Integer
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://en.wikipedia.org/wiki/Abbott_Laboratories", False
http.send
html.body.innerHTML = http.responseText
Set topic = html.getElementsByTagName("tr")(8)
Set titleElem = topic.getElementsByTagName("td")(0)
ThisWorkbook.Sheets(1).Cells(1, 1).Value = titleElem.innerText
End Sub
【问题讨论】:
标签: html excel vba web-scraping