我收到运行时错误91没有为下面的行设置对象或块变量< - Error Here !!
Set html = CreateObject("htmlfile")
html.body.innerHTML = XMLHTTP.ResponseText
Set objResultDiv = html.getElementById("rhs_block")(0) ' <- Error Here!!
Set objH3 = objResultDiv.getElementsByTagName("div")(7).getElementsByTagName("a")(2).getElementsByTagName("span")(0).innerHTML
Cells(i, 2) = objH3
我在Stackoverflow中搜索但没有找到答案。
完整的VBA代码:
Sub XMLHTTP()
Dim url As String, lastRow As Long
Dim XMLHTTP As Object, html As Object, objResultDiv As Object, objH3 As Object
Dim start_time As Date
Dim end_time As Date
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Dim cookie As String
Dim result_cookie As String
start_time = Time
Debug.Print "start_time:" & start_time
For i = 2 To lastRow
url = "https://www.google.co.in/search?q=" & Cells(i, 1) & "&rnd=" & WorksheetFunction.RandBetween(1, 10000)
Set XMLHTTP = CreateObject("MSXML2.serverXMLHTTP")
XMLHTTP.Open "GET", url, False
XMLHTTP.setRequestHeader "Content-Type", "text/xml"
XMLHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0"
XMLHTTP.send
Set html = CreateObject("htmlfile")
html.body.innerHTML = XMLHTTP.ResponseText
Set objResultDiv = html.getElementById("rhs_block")(0)
Set objH3 = objResultDiv.getElementsByTagName("div")(7).getElementsByTagName("a")(2).getElementsByTagName("span")(0).innerHTML
Cells(i, 2) = objH3
DoEvents
Next
end_time = Time
Debug.Print "end_time:" & end_time
Debug.Print "done" & "Time taken : " & DateDiff("n", start_time, end_time)
MsgBox "done" & "Time taken : " & DateDiff("n", start_time, end_time)
End Sub
答案 0 :(得分:0)
html页面上的元素ID必须是唯一的(否则它不会是“标识符”)。因此,只应将一个ID附加到一个元素。但是,浏览器不会检查这一点,分别忽略html文件中的错误。
无论如何,对于你的javascript函数getElementById()
,这意味着它只返回一个单独的元素。
你需要改变:
Set objResultDiv = html.getElementById("rhs_block")(0)
要
Set objResultDiv = html.getElementById("rhs_block")
然后你的objResultDiv
不应再抛出运行时错误91。
getElementsByTagName("p")
一样(返回带有段落标记的所有元素)或getElementsByName("test123")
(返回带有name="test123"
的所有元素)。
您可以从函数名称中判断是返回单个元素还是多个元素。 (getElementById与getElement s ByName)