Reputation: 83
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
Upvotes: 1
Views: 5449
Reputation: 11335
You can try to add lines below to wait for loading the web page completely.
' 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
Below is the full working example:
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
Further, You can try to modify this code example as per your requirement.
Reference:
(1) Automate Internet Explorer (IE) Using VBA
Upvotes: 0
Reputation: 166306
Try something like this (untested)
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
Upvotes: 1