【发布时间】:2021-12-01 05:37:08
【问题描述】:
我一直在使用下面的代码,它给了我一个错误 Run Time Error '91' : Object Variable or With Block not Set 我不知道为什么。
之前它工作正常,但我不知道为什么会发生错误。我已经尝试过搜索 Copy URL from the first Search 的其他解决方案,但它们也不起作用。
此行出现错误Set link = ecoll.getElementsByTagName("a")(0)
如果有人可以提供替代解决方案,那将是很大的帮助。任何帮助将不胜感激。
Sub link()
Dim doc As HTMLDocument
Set doc = New HTMLDocument
Dim lastrow As Long
Dim ecoll As Object
Dim link As Object
Dim t As Date
lastrow = Range("A" & Rows.Count).End(xlUp).Row
t = Now()
Dim reqObj As Object
Set reqObj = CreateObject("MSXML2.XMLHTTP")
For i = 2 To lastrow
reqObj.Open "GET", "https://www.google.co.in/search?q=" & Cells(i, 1) & "&rnd=" & WorksheetFunction.RandBetween(1, 10000), False
reqObj.send
doc.body.innerHTML = reqObj.responseText
Set ecoll = doc.getElementById("rso")
Set link = ecoll.getElementsByTagName("a")(0)
Cells(i, 2) = link.href
Next
Set doc = Nothing
Set reqObj = Nothing
Debug.Print "done" & "Time taken : " & Format(Now() - t, "hh:mm:ss")
MsgBox "Ellapsed Time - " & Format(Now() - t, "hh:mm:ss")
End Sub
【问题讨论】:
-
所以文档不包含id为“rso”的元素,或者id为“rso”的元素不包含任何
<a>s。要么是因为它们实际上并不存在,要么是因为您没有给文档time to parse it。 -
也许尝试在解析之前添加延迟。 @GSerg 可能只是在做某事。哦,请您按“调试”以显示代码在哪一行中断?
-
错误是否发生在它之前工作的完全相同的站点上?正如@GSerg 所说,我的意思是完全相同的,HTML 可能已经改变。当它不工作时,你能确认它有你要捕获的标签吗?
-
好吧,这就是它给出错误的问题,因为它没有在单元格中找到该值。我曾尝试使用解析,但我错了,如果它不打扰你,请分享解决方案。我会很感激帮助。 @GSerg
-
这一行出现错误
Set link = ecoll.getElementsByTagName("a")(0)
标签: excel vba web-scraping