【发布时间】:2018-10-25 12:48:29
【问题描述】:
我正在尝试编写一个工具,让我的同事可以快速计算配对城市列表之间的距离,以完成一项季节性但对我们部门来说非常重要的任务。
我目前通过 Google Maps Distance API 使用它,但他们的政策和支付方式的不断变化正在变成一个真正的问题,因为我们只是在需要使用它时才发现该工具已停止工作。
这就是为什么我决定解决这个问题并摆脱对 API 的需求。这是我的第一个 Scraping 项目,所以我确信有更好的编码方法,但到目前为止我的解决方案是:
Sub Scrape2()
Dim IE As Object
Dim dist As Variant
Dim URL As String
Dim i As Integer
'Creates an Internet Explorer Object
Set IE = CreateObject("InternetExplorer.application")
URL = "https://www.entrecidadesdistancia.com.br"
With IE
.Visible = False ' "True" makes the object visible
.navigate URL 'Loads the website
'Waits until the site's ready
While IE.Busy
DoEvents
Wend
Do While .Busy
Loop
'Selects "origin" field and inserts text
.Document.getElementById("origem").Value = "Jandira, SP - Brasil"
'Selects "destination" field and inserts text
.Document.getElementById("destino").Value = "Cotia, SP - Brasil"
'Presses the GO button
For Each Button In .Document.getElementsByTagName("button")
Button.Click
Exit For
Next
'Waits until the site's ready
Do While .Busy
Loop
Do While .Busy
Loop
dist = .Document.getElementById("distanciarota").innerText
MsgBox (dist)
End With
IE.Quit
Set IE = Nothing
End Sub
它打开一个 Internet Explorer 对象,将两个城市(我最终将用来自我的工具的信息替换)插入正确的字段,点击 GO,加载下一页并应该将我需要的数字放入 MessageBox (当我得到这个工作时,我将用目标单元格替换)。
我的最后一个问题是,有一半的时间,宏会停止并在这一行声明“运行时错误'424':需要对象”:
.Document.getElementById("origem").Value = "Jandira, SP - Brasil"
或者在这一行:
dist = .Document.getElementById("distanciarota").innerText
我设法通过在两个“问题”行之前插入另一个等待期来解决这个问题,但这确实比我想要的更慢。
不过,现在它总是会到达最后一行,但是当它到达时,我的 MessageBox 会出现空白。
这是我需要的信息:
<strong id="distanciarota">12.4 km</strong>
来自这个网站:https://www.entrecidadesdistancia.com.br/calcular-distancia/calcular-distancia.jsp
非常感谢任何将其放入变量或工作表单元格的帮助。
【问题讨论】:
-
您认为这会比使用 API 更可靠吗?
-
我正在测试一些东西。我现在需要的只是“更稳定”。
标签: excel vba web-scraping excel-2010