Error on getting the URL result of a Google search.

后端 未结 3 2039
轻奢々
轻奢々 2021-01-27 00:26

I am new to VBA, and I figured that trying to code is the best way to code. Anyway, I am trying to code a macro that will get first URL of a Google search result, but I\'m getti

3条回答
  •  忘掉有多难
    2021-01-27 01:03

    Here is simplified code for the same method.

    Sub xmlHttp()
        Dim url As String,
            lastRow As Long,
            XMLHTTP As Object, 
            html As Object,
            objResultDiv As Object,
            objH3 As Object,
            link As Object
    
        lastRow = Range("A" & Rows.Count).End(xlUp).Row
        For i = 2 To lastRow
            url = "https://www.google.co.in/search?q=" & Cells(i, 1)
            Set xmlHttp = CreateObject("MSXML2.XMLHTTP")
            xmlHttp.Open "GET", URL, False
            xmlHttp.setRequestHeader "Content-Type", "text/xml"
            xmlHttp.send
            Set html = CreateObject("htmlfile")
            html.body.innerHTML = xmlHttp.ResponseText
            Set objResultDiv = html.getelementbyid("rso")
            numb_H3 = objResultDiv.getElementsByTagName("H3").Length
            If numb_H3 > 0 Then
                Set objH3 = objResultDiv.getElementsByTagName("H3")(0)
                Set link = objH3.getElementsByTagName("a")(0)
                Range(i, 2) = link
            Else
            End If
            DoEvents
        Next
    End Sub
    

提交回复
热议问题