找不到错误脚本如何完美运行的任何逻辑?

Can't find any logic how the faulty script works flawlessly?

我在 vba 中编写了一个脚本,使用 IE 从网页中获取不同酒店名称的标题。酒店名称通过分页遍历多个页面

我的抓取器可以在解析每个页面的标题时继续成功点击下一个按钮,直到没有更多的点击可以执行。解析器正在做的工作非常完美。我只想知道我在下面提出的一个简单逻辑。

我的问题:即使我没有在 .click 之后使用此 Set Htmldoc = IE.document 行,每个页面的内容如何正确显示?启动点击后,抓取工具会转到包含新内容的新页面。当我定义的 do loopwith IE 块之后出现时,它如何更新每个页面的新内容?

这是脚本:

Sub GetTitles()
    Const Url As String = "https://www.tripadvisor.com/Hotels-g147237-Caribbean-Hotels.html"
    Dim IE As New InternetExplorer, Htmldoc As HTMLDocument, post As Object, R&

    With IE
        .Visible = True
        .navigate Url
        While .Busy = True Or .readyState < 4: DoEvents: Wend
        Set Htmldoc = .document
    End With

    Do
        For Each post In Htmldoc.getElementsByClassName("listing") ''how this "Htmldoc" gets updated
            With post.getElementsByClassName("property_title")
                If .Length Then R = R + 1: Cells(R, 1) = .Item(0).innerText
            End With
        Next post

        If Not Htmldoc.querySelector(".standard_pagination span[onclick*='pagination_next']") Is Nothing Then
            Htmldoc.querySelector(".standard_pagination span[onclick*='pagination_next']").Click
            Application.Wait Now + TimeValue("00:00:05")

            ''I didn't use anything like "Set Htmldoc = IE.document" but it still works flawlessly 
        Else:
            Exit Do
        End If
    Loop
    IE.Quit
End Sub

Set Htmldoc = .document

获取指向 DOM 的指针。当它更改时,Htmldoc 指向新内容。不需要做一个新的 Set Htmldoc

脚本没有问题。不过,你在没有完全理解的情况下使用肯定很麻烦。


执行此操作时 Set Htmldoc = .document 您正在设置 IE 的文档供以后使用。

当您执行此操作时,Htmldoc.querySelector(".standard_pagination span[onclick*='pagination_next']").Click javascript 发挥作用并且 更新 页面(即文档)的内容。

您可能认为文档已更改,但只是更新而已。实际上,根本没有导航发生。


添加以下内容,看看 page/document 是如何保持不变的,只是内容发生了变化。

            '/ Url before Next button click
            Debug.Print "Before Click " & Htmldoc.Url
            Htmldoc.querySelector(".standard_pagination span[onclick*='pagination_next']").Click
            '/ Url after Next button click
            Debug.Print "After Click " & Htmldoc.Url

自文档以来,一旦设置保持不变并且更新的内容具有相同的layout/DOM (这就是大多数程序员编码的方式,很可能所有页面都使用模板呈现) 因此你的代码工作得很好。网络到网络的 do 循环,没有任何变化。