且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Excel VBA中,如何检查网页是否完全加载?

更新时间:2023-11-28 21:55:34

网页的功能非常不同,因此没有适合所有网页的解决方案.

Functionality of webpages is very different, so there is no solution that will fit to all of them.

关于您的示例,您的解决方法是一个可行的解决方案,代码可能如下所示:

Regarding your example, your workaround is a working solution, the code might be like:

Sub TestIE()

    Dim q

    With CreateObject("InternetExplorer.Application")
        .Visible = True
        .Navigate "https://www.homedepot.ca/en/home/p.dry-cloth-refills-32---count.1000660019.html"
        ' Wait IE
        Do While .readyState < 4 Or .Busy
            DoEvents
        Loop
        ' Wait document
        Do While .document.readyState <> "complete"
            DoEvents
        Loop
        ' Wait element
        Do
            q = .document.querySelector(".product-total-price").innerText
            If Left(q, 1) <> "-" Then Exit Do
            DoEvents
        Loop
        .Quit
    End With
    Debug.Print q

End Sub

无论如何,您需要使用浏览器开发工具 (F12) 查看网页加载过程、XHR 和 DOM 修改.按照这种方式,您可能会发现众多 XHR 之一以 JSON 格式返回价格.它在页面加载时价格出现之前登录浏览器开发人员工具的网络选项卡.XHR 是由其中一个加载的 JS 生成的,特别是在页面加载事件之后.试试这个网址(我只是从网络标签中复制了它):

Anyway, you need to look into the webpage loading process, XHRs and DOM modifications, using browser developer tools (F12). Going that way, you may find that one of the numerous XHRs returns the price in JSON format. It's logged on network tab of browser developer tools right before the price appearing while the page is loading. That XHR is made by one of the loaded JS, notably after the page loaded event. Try this URL (I just copied it from network tab):

https:///www.homedepot.ca/homedepotcacommercewebservices/v2/homedepotca/products/1000660019/localized/9999?catalogVersion=Online&lang=en

因此,您可以复制该 XHR 并通过拆分来提取价格:

So you may just reproduce that XHR and extract the price by splitting:

Sub TestXHR()

    Dim q

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.homedepot.ca/homedepotcacommercewebservices/v2/homedepotca/products/1000660019/localized/9999?catalogVersion=Online&lang=en", False
        .Send
        q = .ResponseText
    End With
    q = Replace(q, " : ", ":")
    q = Split(q, """displayPrice""", 2)(1)
    q = Split(q, """formattedValue"":""", 2)(1)
    q = Split(q, """", 2)(0)
    Debug.Print q

End Sub

但同样,没有常见的情况.

But again, there is no common case.

你也可以使用 JSON 解析器,看看一些例子.

You may also use JSON parser, take a look at some examples.