VBA等待网页中的所有内容完全加载

问题描述 投票:1回答:2

我试图在导航到网站后从网站上提取一些信息,但我似乎无法等到它完全加载。我一直在尝试循环,直到(0)的类包含文本。谁知道我做错了什么?

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
html vba internet-explorer web-scraping extract
2个回答
1
投票

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

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

0
投票

您可以尝试在下面添加行以等待完全加载网页。

' Wait while IE loading...
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
    Do While IE.ReadyState = 4: DoEvents: Loop   'Do While
    Do Until IE.ReadyState = 4: DoEvents: Loop   'Do Until

以下是完整的工作示例:

Sub Automate_IE_Load_Page()
'This will load a webpage in IE
    Dim i As Long
    Dim URL As String
    Dim IE As Object
    Dim objElement As Object
    Dim objCollection As Object

    'Create InternetExplorer Object
    Set IE = CreateObject("InternetExplorer.Application")

    'Set IE.Visible = True to make IE visible, or False for IE to run in the background
    IE.Visible = True

    'Define URL
    URL = "https://www.automateexcel.com/excel/"

    'Navigate to URL
    IE.Navigate URL

    ' Statusbar let's user know website is loading
    Application.StatusBar = URL & " is loading. Please wait..."

    ' Wait while IE loading...
    'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
    Do While IE.ReadyState = 4: DoEvents: Loop   'Do While
    Do Until IE.ReadyState = 4: DoEvents: Loop   'Do Until

    'Webpage Loaded
    Application.StatusBar = URL & " Loaded"

    'Unload IE
    Set IE = Nothing
    Set objElement = Nothing
    Set objCollection = Nothing

End Sub

此外,您可以尝试根据您的要求修改此代码示例。

参考:

(1)Automate Internet Explorer (IE) Using VBA

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.