【发布时间】:2019-05-18 12:55:54
【问题描述】:
我正在尝试创建一个宏,它从 Excel 中提取地址列表并将每个地址输入到 Google 地图中。
然后,它将地址行、城市/邮编和国家/地区从 Google 地图拉回 Excel。
它可以从谷歌地图中抓取信息。
Sub AddressLookup()
Application.ScreenUpdating = False
For i = 1 To Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
Dim IE As InternetExplorer
Dim itemELE As Object
Dim address As String
Dim city As String
Dim country As String
Set IE = New InternetExplorer
IE.Visible = True
IE.navigate "https://www.google.com/maps"
Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE
Dim Search As MSHTML.HTMLDocument
Set Search = IE.document
Search.all.q.Value = Cells(i, 1).Value
Dim ele As MSHTML.IHTMLElement
Dim eles As MSHTML.IHTMLElementCollection
Set eles = Search.getElementsByTagName("button")
For Each ele In eles
If ele.ID = "searchbox-searchbutton" Then
ele.click
Else
End If
Next ele
For Each itemELE In IE.document.getElementsByClassName("widget-pane widget-pane-visible")
address = itemELE.getElementsByClassName("section-hero-header-description")(0).getElementsByTagName("h1")(0).innerText
city = itemELE.getElementsByClassName("section-hero-header-description")(0).getElementsByTagName("h2")(0).innerText
country = itemELE.getElementsByClassName("section-hero-header-description")(0).getElementsByTagName("h2")(1).innerText
Next
Cells(i, 2).Value = Trim(address)
Cells(i, 3).Value = Trim(city)
Cells(i, 4).Value = Trim(country)
MsgBox country
Next
Application.ScreenUpdating = True
End Sub
【问题讨论】:
-
也许改用 Google 的 Map API?
-
绝对使用谷歌的Geocoding API,而不是缓慢且不可靠(丑陋)的抓取
-
我以前从未使用过 API,所以我什至不知道从哪里开始
-
请参阅上面的链接开始,但我注意到他们更改了使用条款。不知道现在什么是免费的。您可以使用VBA-Web 发送请求并解析响应。作为免费替代品(但请尊重Usage Policy),您可以使用Nominatim Open Street Map。对于大量使用,请安装您自己的 OSM。也许我稍后会创建一个 VBA-Web 示例作为答案。
-
您应该提供测试输入和预期输出。
标签: html excel vba web-scraping