如果页面上存在元素,请检查VBA [英] Check with VBA if an element exists on the page

查看:627
本文介绍了如果页面上存在元素,请检查VBA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有15,000种产品,我需要知道它们是X,Y还是Z.下面的代码检查亚马逊,看看产品是否是一种XYZ。

I have 15,000 products and I need to know if they're X, Y or Z. The code below checks on amazon to see if a product is a type of XYZ.

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

God help me, it actually works. The only exception is when it searches a product no longer sold by Amazon. Then the element ID that I'm looking for which contains the product description that I'm searching doesn't exist on the page, and the code breaks on line

text = document.getelementbyID("result_0").innertext

with错误对象变量或未设置块变量。

with the error "Object variable or With block variable not set".

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

How do I check if the element exists before proceeding with the rest of the code?

谢谢!

Sam

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


推荐答案

Ryan的答案是正确的。

Ryan's answer is the correct.

set Element = document.getelementbyID(result_0)

set Element = document.getelementbyID("result_0")

这篇关于如果页面上存在元素,请检查VBA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆