首页 > 解决方案 > VBA wait for everything in a webpage to completely load

问题描述

I'm trying to pull some information from a website after navigating to it but I can't seem to wait until it completely loads. I've been trying to loop until the class at (0) contains text. Anyone know what I'm doing wrong?

Sub test()

Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True

Dim elements2 As IHTMLElementCollection

    IE.Navigate "https://www.facebook.com/marketplace/item/955559644646354/"
        Do While IE.Busy Or IE.readyState <> 4
            DoEvents
        Loop
Dim x
x = 0
Do Until x = 1
Set elements2 = IE.document.getElementsByClassName("_3cgd")

If WorksheetFunction.IsText(elements2(0).innerText) = True Then
    MsgBox ((elements2(0).innerText))
    x = 1
  Else
  Application.Wait Now + #12:00:01 AM#
  End If
Loop

End Sub

标签: htmlvbainternet-explorerweb-scrapingextract

解决方案


尝试这样的事情(未经测试)

Dim t, elements2, txt

t = Timer
txt = ""

Do 
    Set elements2 = IE.document.getElementsByClassName("_3cgd")
    If elements2.length > 0 Then
        txt = elements2(0).innerText
        If Len(txt) > 0 Then Exit Do
    End If

    If (Timer - t) > 10 Then Exit Do 'exit if too long waiting

    Application.Wait Now + TimeSerial(0, 0, 1)
Loop

推荐阅读