使用抓取 'elementbyID' 当 ID 不存在时如何返回值 0?



您好,我下面有一些代码可以从网站上抓取数据。

我正在努力解决的是 Element id 并不总是存在于这个网站上(这很好( - 但如果是这种情况,我希望该值仅返回为 £0。

相反,我得到"运行时错误'424'需要对象。

这是因为我的ID"X123"不在网站上。

任何帮助将不胜感激。

Option Explicit

Sub getdata((

Dim wb As Object
Dim i As Integer
Dim sURL As String
Dim getprice As Object
Dim myValue As String

For i = 8 To Sheets("Sheet1").Range("B34").Value
Set wb = CreateObject("internetExplorer.Application")
sURL = Cells(i, 1)
wb.Navigate sURL
wb.Visible = False
Do While wb.Busy = True Or wb.ReadyState <> 4: DoEvents: Loop
Set getprice = wb.Document.getElementById("X123")
myValue = getprice.innerText
Sheets("Sheet1").Cells(i, 2).Value = myValue
wb.Quit
Set wb = Nothing
Next i

结束子

添加一些错误处理

On Error Resume Next
Set getprice = wb.Document.getElementById("X123")
On Error GoTo 0
If getPrice Is Nothing Then 
myValue = "£0"  '<=Assuming £ is included and not formatted in sheet
Else
myValue = getprice.innerText
End If

最新更新