谷歌搜索宏

时间:2014-01-18 13:44:38

标签: excel vba google-search

我需要对my previous question中的宏进行一些修改,例如列c中的搜索结果第一个链接,列d中的第二个链接,列e中的第三个链接等,最多分别为5个或更多链接。

这是宏

Sub XMLHTTP()

   Dim url As String, lastRow As Long
   Dim XMLHTTP As Object, html As Object, objResultDiv As Object, objH3 As Object, link 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("rso")
      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
      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

1 个答案:

答案 0 :(得分:1)

为了将每个超链接放在第1行,C列和Seq。列中,请修改以下行:

Cells(i, 2) = str_text
Cells(i, 3) = link.href

并将它们更改为这一行:

Cells(1, i+2) = link.href

语句Cells(r, c)表示要分配的位置,因此代码最初是将每个结果放在&amp;链接在一个新行上,在列B和C中(Cells(i, 2)将是B列,等等)你只需修改该语句就可以将数据放到你想要的位置。