Excel VBA HTML嵌套QuerySelector

时间:2018-11-12 16:38:32

标签: html excel vba web-scraping css-selectors

考虑以下HTML页面摘录:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<div class="BoxBody">
<span class="txt">20 Records found. </span>
<p style="text-align: right;"><span class="txt">[First/Previous] &nbsp;1&nbsp;, <a class="page" href="javascript:paginacao('paginar','2');" title="Go to page 2">2</a> [<a class="page" title="Next page" href="javascript:paginacao('paginar','next');">Next</a>/<a class="page" title="Last page" href="javascript:paginacao('paginar','last');">Last</a>]</span></p>
<br>
<span class="txt">25 Records found. </span>
<p style="text-align: right;"><span class="txt">[First/Previous] &nbsp;1&nbsp;, <a class="page" href="javascript:paginacao('paginar2','2');" title="Go to page 2">2</a> [<a class="page" title="Next page" href="javascript:paginacao('paginar2','next');">Next</a>/<a class="page" title="Last page" href="javascript:paginacao('paginar2','last');">Last</a>]</span></p>
</div>
</body>
</html>

我正在尝试获取带有“下一页”页面anchor(如果有的话)的href标签。

我在使用Firefox的控制台中对此进行了尝试,并且可以正常工作:

document.querySelector(".BoxBody > p:nth-child(2) > span:nth-child(1)").querySelector("a[title='Next page']")

我也使用querySelector编写了一个示例VBA代码,但是失败了,出现了Invalid argument

Sub test()

Dim oFSO As Object, paginator As Object
Dim oFS As Object, sText As String

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFS = oFSO.OpenTextFile(ThisWorkbook.Path & "\example.html")

Do Until oFS.AtEndOfStream
    sText = oFS.ReadAll()
Loop


Dim html As HTMLDocument, html2 As Object
Set html = New HTMLDocument
Set html2 = html
html2.Write sText

Set paginator = html.querySelector(".BoxBody > p:nth-child(2) > span:nth-child(1)").querySelector("a[title='Next page']")

End Sub

是什么原因造成的? p:nth-child(2)标识符? 我应该如何使用VBA提取该元素?

1 个答案:

答案 0 :(得分:3)

nth-child(2)在VBA中不受支持,并确实导致了错误消息。您不能使用:nth-child():nth-of-type()。在处理伪类的库中几乎没有实现。您可以有趣地使用first-child。您还会发现在哪些对象上可以链接querySelector受到限制。

Dim ele As Object, iText As String
Set ele = html.querySelector(".BoxBody > p > span:first-child > a[title='Next page']")

On Error Resume Next
iText = ele.href
On Error GoTo 0

If iText = vbNullString Then '<== This assumes that the href has a value otherwise use an On Error GoTo which will then handle the error and print "no href"
    Debug.Print "No href"
Else
   Debug.Print "href"
End If