我编写了一个代码,通过google使用vba解析来自多个站点的数据。它可以刮除标记元素"h3“和"a”,而不管搜索是什么。但是,如果可能的话,我想解析任何搜索的名称或电话号码。提前谢谢你的帮助。
Sub GoogleSearch()
Dim http As New MSXML2.XMLHTTP60, html As New HTMLDocument, hmm As New HTMLDocument
Dim topics As Object, post As Object, link As Object, posts As Object
Dim url As String, z As String
Dim i As Long, LRow As Long
LRow = Range("A" & Rows.Count).End(xlUp).Row
For i = 3 To LRow
url = "https://www.google.co.in/search?q=" & Cells(i, 1)
http.Open "GET", url, False
http.setRequestHeader "Content-Type", "text/xml"
http.send
html.body.innerHTML = http.responseText
Set topics = html.getElementById("rso")
Set post = topics.getElementsByTagName("H3")(0)
Set link = post.getElementsByTagName("a")(0)
Cells(i, 2) = link.innerText
Cells(i, 3) = link.href
z = link.href
http.Open "GET", z, False
http.send
hmm.body.innerHTML = http.responseText
Set posts = hmm.getElementsByClassName("phone")
If Not posts(0) Is Nothing Then
Cells(i, 4) = posts(0).innerText
Else
Cells(i, 4).Value = "Phone Not Found"
End If
Next i
End Sub发布于 2017-02-14 14:09:56
我编写了一个代码来使用google解析来自多个站点的数据。
不完全同意。你所写的是非常具体和不灵活的代码,它要求有一个“电话”类,否则会出现错误。一旦你做了这个http.Open "GET", z, False,你就会导航到一个新的网站,而且没有理由相信Yellopage和McDonalds会分享甚至远程相同的结构。此时,您所做的只是不够灵活,无法处理(不同的)网站可能采取的无限结构:
http.send
hmm.body.innerHTML = http.responseText
Set posts = hmm.getElementsByClassName("phone")
Cells(i, 4) = posts(0).innerText当您Set posts = hmm...时,您假设在您刮过的每个网站上都必须有一个带有ClassName= "phone“的元素。如果没有这样的元素,那么错误将引发(对象所需的)。
为了获得任何元素,您需要了解您正在抓取的站点的结构,但是有几种方法可以这样做:
getElementsByTagName或getElementsByClassName的索引调用(您目前正在做的事情),但这需要您知道标记名或类名getElementsByTagName返回的集合上迭代时匹配某些条件,如果找到条件,则使用Exit ForgetElementByID (如果ID标记可用,则它是唯一标识符)xpath标识符。如果您提供被解析的网页的示例源代码,则可能更容易给您提供具体的帮助,但是,由于您显然试图刮除各种网站,因此不太可能获得单一的解决方案。
我可能要做的是,跟进你的评论如下:
http.Open "GET", z, False
http.send
hmm.body.innerHTML = http.responseText
Set posts = hmm.getElementsByClassName("phone")
If posts Is Nothing Then'# This condition is True if no "phone" element exist
cells(1,4).Value = "phone not found at " & z
Else
Cells(i, 4) = posts(0).innerText
End If
Next i这至少会在没有错误的情况下运行,并且它将识别不包含"phone“类的URL。然后,您可以检查这些网页的源HTML,并且可以修改代码以处理其他情况。
您可以尝试摄取整个结果并使用正则表达式从普通HTML源提取电话号码,在这种情况下,这可能是最可靠的。
https://stackoverflow.com/questions/42227792
复制相似问题