使用 VBA 检查页面上是否存在元素

Sam*_*Sam 2 excel internet-explorer vba getelementbyid

我有 15,000 种产品,我需要知道它们是 X、Y 还是 Z。下面的代码在亚马逊上检查产品是否属于 XYZ 类型。

上帝帮助我,它确实有效。唯一的例外是当它搜索亚马逊不再销售的产品时。然后我正在寻找的包含我正在搜索的产品描述的元素 ID 在页面上不存在,并且代码在线中断

text = document.getelementbyID("result_0").innertext
Run Code Online (Sandbox Code Playgroud)

出现错误“对象变量或块变量未设置”。

在继续执行其余代码之前,如何检查元素是否存在?

谢谢!

山姆

Sub LetsAutomateIE()

Dim barcode As String
Dim rowe As Integer
Dim document As HTMLDocument
Set ie = CreateObject("InternetExplorer.Application")
Dim Element As HTMLDivElement
Dim text As String
Dim pos As Integer

rowe = 2

While Not IsEmpty(Cells(rowe, 2))

barcode = Cells(rowe, "B").Value

With ie
.Visible = False
.navigate2 "https://www.amazon.co.uk/s/ref=nb_sb_noss_1?url=search-    
alias%3Daps&field-keywords=" & barcode
Do Until ie.readyState = 4
Loop
End With

Set document = ie.document

text = document.getElementById("result_0").innerText

If InStr(text, "X") Or InStr(text, "Y") Or InStr(text,     
"Z") <> 0 Then pos = 1

If pos <> 0 Then Cells(rowe, 4) = "Y" Else Cells(rowe, 4) = "N"

rowe = rowe + 1

Wend

Set ie = Nothing

End Sub
Run Code Online (Sandbox Code Playgroud)

小智 5

发布替代方案,以防最佳答案对其他人不起作用:

使用 IsObject() 检查后,我仍然收到运行时错误“91”

如果 ObjIE 是 InternetExplorer 对象,则 IsObject() 工作正常,但我使用的是 InternetExplorerMedium 对象并且不得不用它来验证,因为它返回的是空对象:

If Not objIE.document.getElementById("e164NumberMask") Is Nothing Then
    'do true stuff
Else
    'do false stuff
End If
Run Code Online (Sandbox Code Playgroud)