捕获错误,当找不到 getElementById

Catch error, when not finding getElementById

我正在从网页上抓取一些数据,想切换我的 id,但找不到一个 ID。

我试过:

If IsError(Docx.getElementById("priceblock_ourprice").innerText) Then
    price = Docx.getElementById("priceblock_saleprice").innerText
Else
     price = Docx.getElementById("priceblock_ourprice").innerText
End If

但是,我在 IsError(Docx.getElementById("priceblock_ourprice").innerText)Object variable or With Block is not set.

处收到错误

任何建议,如何 "catch" Docx.getElementById("priceblock_ourprice").innerText 处的错误?

感谢您的回复!

尝试使用 IsObject Funcion -> IsObject

你的情况IF IsObject(Docx.getElementById("priceblock_ourprice")) THEN (...)

如果您尝试按 ID 定位元素,您对非破坏性捕获的选择是有限的,但您可以 Set getElementById 的 return 并且不检查任何内容.

dim el as MSHTML.IHTMLElement

on error resume next
set el = Docx.getElementById("priceblock_ourprice")
on error goto 0
If not el is nothing  Then
    price = Docx.getElementById("priceblock_ourprice").innerText
Else
    price = Docx.getElementById("priceblock_saleprice").innerText
End If

如果您按集合定位元素,则可以循环遍历它们以查找第二个唯一标识符,然后再访问它们的属性之一(例如 .innerText)。