首页 > 解决方案 > 使用 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("*") 出现错误,因为该对象不支持该方法。

标签: htmlexcelvba

解决方案


更干净,更快,将是使用 css 查询组合您的要求(一个类的所有子级),然后循环返回的 nodeList 例如

With html.querySelectorAll(".chapter > *")
    For i = 0 To .Length - 1
        Worksheets("Output").Range("A" & i + 1) = .Item(i).innerText
    Next
End With

推荐阅读