html - 使用 VBA 获取 div 中的所有元素
问题描述
我正在尝试抓取 Project Gutenberg。
我可以使用 .getElementsByClassName("chapter") 来获取包含章节的 div。但是,我无法将该 div 中的所有元素作为一个集合,然后我可以对其进行迭代。
Sub getZ()
Dim H As Object, C As New DataObject, stryn&, cptr%, html As New HTMLDocument, p As HTMLHtmlElement, para As Object, i&
Set H = CreateObject("WinHTTP.WinHTTPRequest.5.1")
Application.ScreenUpdating = False
With H
.SetAutoLogonPolicy 0
.SetTimeouts 0, 0, 0, 0
.Open "GET", "https://www.gutenberg.org/files/8164/8164-h/8164-h.htm", False
.Send
.WaitForResponse
End With
html.body.innerHTML = H.ResponseText
Set para = html.getElementsByClassName("chapter").getElementsByTagName("*")
i = 1
For Each p In para
Worksheets("Output").Range("A" & i & "") = p.innerText
i = i + 1
Next
Application.ScreenUpdating = True
End Sub
getElementsByTagName("*") 出现错误,因为该对象不支持该方法。
解决方案
更干净,更快,将是使用 css 查询组合您的要求(一个类的所有子级),然后循环返回的 nodeList 例如
With html.querySelectorAll(".chapter > *")
For i = 0 To .Length - 1
Worksheets("Output").Range("A" & i + 1) = .Item(i).innerText
Next
End With
推荐阅读
- c# - 尝试插入数据时,Entity Framework Core 中的一对多关系出现错误
- javascript - 使用 JSON 数据制作 CanvasJS 图表
- r - 如何根据颜色的具体要求制作散点图?
- android - 查看寻呼机片段应加载 1 次以显示来自 firebase 的数据(异步任务)
- ios - 关闭 MMDrawer Controller 后,swift4 中会调用哪个视图控制器生命周期方法?
- java - 如何在netbeans平台的任务栏中显示登录页面
- jenkins - 使用 java 程序在 jenkins 中运行测试用例
- android - 如何自动化没有在 iOS 平台上编写的任何 UI 的库?
- angular - 如何让 Bootstrap 组件与 Angular 6 一起使用?
- java - Android Java 多数组初始化