gpt4 book ai didi

VBA/DOM - 根据属性获取元素

转载 作者:行者123 更新时间:2023-12-02 16:44:10 24 4
gpt4 key购买 nike

Windows 7 上的 Excel 2013。XPath/Javascript/jQuery 超出范围。

我正在尝试迭代页面中选择的 div 元素,即具有特定 data-level 属性的元素。

我当前的方法是 similar to this ,但我无法找到一种非手动方式来根据属性选择元素。我最接近的是这样的:

With CreateObject("WINHTTP.WinHTTPRequest.5.1")
.Open "GET", url, False
.Send
pHTML.body.innerHTML = .ResponseText
End With

Set eCollection = pHTML.getElementsByClassName("chapter").getElementsByTagName("div")

For i = 0 To eCollection.Length
If eCollection(i).getAttribute("data-level") >= 0 Then ' Throw cake
Next i

虽然我确信它是可行的(如果不优雅),但如果仅考虑当我开始在 中查找特定元素和元素序列时循环最终将有多大,那么它似乎不是最佳的这些元素

所以我正在寻找一种方法来做这样的事情:

For Each pElement In pHTML.getElementsByClassName("chapter").getElementsByTagName("div").getElementsByAttribute("data-level")
' Throw cake at the element
Next

我知道没有方法 getElementsByAttribute,因此出现了问题。
这里是否有一些我看不到的方法,或者我是否被锁定为手动迭代?

或者,如果我改变当前创建 IE 实例的方法,就像 this answer ,我可以使用 querySelectorAll 来得到类似于我上面概述的结果吗?

最佳答案

对于其他人来说,可以说,外壳看起来像这样:

Sub ScrapeWithHTMLObj(url As String, domClassName As String, domTag As String, domAttribute As String, domAttributeValue As String)
' Dependencies:
' * Microsoft HTML Object Library

' Declare vars
Dim pHTML As HTMLDocument
Dim pElements As Object, pElement As Object

Set pHTML = New HTMLDocument

' Basic URL healthcheck
Do While (url = "" Or (Left(url, 7) <> "http://" And Left(url, 8) <> "https://"))
MsgBox ("Invalid URL!")
url = InputBox("Enter new URL: (0 to terminate)")
If url = "0" Then Exit Sub
Loop

' Fetch page at URL
With CreateObject("WINHTTP.WinHTTPRequest.5.1")
.Open "GET", url, False
.Send
pHTML.body.innerHTML = .ResponseText
End With

' Declare page elements
Set pElements = pHTML.getElementsByClassName(domClassName)
Set pElement = pElements(0).getElementsByTagName(domTag)

' Extract only elements with wanted attribute
pEleArray = getElementsByAttribute(pElement, domAttribute, domAttributeValue)

For Each e In pEleArray
' Do stuff to elements
Debug.Print e.getAttribute(domAttribute)
Next
End Sub

如果你走这条路,你还需要这样的东西:

Function getElementsByAttribute(pObj As Object, domAttribute As String, domAttributeValue As String) As Object()
Dim oTemp() As Object
ReDim oTemp(1 To 1)

For i = 0 To pObj.Length - 1
'Debug.Print pObj(i).getAttribute(domAttribute)
If pObj(i).getAttribute(domAttribute) = domAttributeValue Then
Set oTemp(UBound(oTemp)) = pObj(i)
ReDim Preserve oTemp(1 To UBound(oTemp) + 1)
End If
Next i

ReDim Preserve oTemp(1 To UBound(oTemp) - 1)

getElementsByAttribute = oTemp
End Function

显然,根据 HTML 树的不同,您需要更改子目录中将哪些元素归零。对于我在测试中使用的网站,这种结构运行得非常完美。

用法示例:
调用 ScrapeWithHTMLObj("https://somesite", "chapter-index", "div", "data-level", "1")

它会进入第一个名为chapter-index的类,选择所有带有div标签的元素,最后提取所有包含属性data-level的元素 值为 1

关于VBA/DOM - 根据属性获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40282180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com