Error on getting the URL result of a Google search.

后端 未结 3 1960
轻奢々
轻奢々 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 00:53

    In the zero result case, H3 is empty so modify your code like this to handle this case

      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)
    
          str_text = Replace(link.innerhtml, "<EM>", "")
          str_text = Replace(str_text, "</EM>", "")
    
          Cells(i, 2) = str_text
          Cells(i, 3) = link.href
      **Else**
      **End If**
      DoEvents
    

    Next

    0 讨论(0)
  • 2021-01-27 00:57

    One simple workaround--though not the best--is to skip the error.

    Try the following modification:

    start_time = Time
    Debug.Print "start_time:" & start_time
    
    On Error Resume Next '--Add this part.
    For i = 2 To lastRow
    

    Other options include a true error handling part, something that returns a value when your search returns nothing.

    Let us know if this helps.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题