【发布时间】:2016-09-04 05:09:29
【问题描述】:
我目前正在尝试使用 VBA 从一个名为 X-Rates 的网站上抓取一些汇率。我目前的问题是运行时间太长。我已将其范围缩小到我的 IE 对象的 Do Events。
我的问题:有没有更好的方法(也许代码效率更高),或者我的逻辑有缺陷?
代码的作用如下:
1 - 每个国家的循环 (1-9 = offsetCurr);
2- 转换为汇率并在单元格上保存价值
'Define variables
Dim strElm As String
Dim i As Integer
Dim ie As InternetExplorer
Dim period As Variant
Dim offsetCurr As Integer
Dim offsetDesc As String
'Define period
period = Application.InputBox("What's the year and period?", "Period", , , , , 2)
'Define start row
i = 2
Application.ScreenUpdating = False
On Error GoTo ErrHandler
For offsetCurr = 1 To 9
If offsetCurr = 1 Then
'ARS to EURO
Set ie = New InternetExplorer
offsetDesc = "ARS"
Cells(i, 1).Value = period
Cells(i, 2).Value = offsetDesc
ie.navigate "http://www.x-rates.com/calculator/?from=ARS&to=EUR&amount=1"
Do While ie.readyState <> READYSTATE_COMPLETE
DoEvents
Loop
d = ie.document.getElementsByClassName("ccOutputRslt")(0).innerText
strElm = d
Cells(i, 3).Value = strElm
ie.Quit
Set ie = Nothing
'ARS to USD
Set ie = New InternetExplorer
ie.navigate "http://www.x-rates.com/calculator/?from=ARS&to=USD&amount=1"
Do While ie.readyState <> READYSTATE_COMPLETE
DoEvents
Loop
d = ie.document.getElementsByClassName("ccOutputRslt")(0).innerText
strElm = d
Cells(i, 4).Value = strElm
'Quit IE for automation purposes
ie.Quit
Set ie = Nothing
'ARS to GBP
Set ie = New InternetExplorer
ie.navigate "http://www.x-rates.com/calculator/?from=ARS&to=GBP&amount=1"
Do While ie.readyState <> READYSTATE_COMPLETE
DoEvents
Loop
d = ie.document.getElementsByClassName("ccOutputRslt")(0).innerText
strElm = d
Cells(i, 5).Value = strElm
ie.Quit
Set ie = Nothing
End If
ErrHandler:
If Err.Number <> 0 Then
Msg = "Error #" & Str(Err.Number) & " was generated by " & Err.Source & "." & Chr(13) & "Error description: " & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
Exit Sub
End If
End Sub
我知道代码量很大,如果需要,我可以编辑问题以使其更简单。
【问题讨论】:
-
我在这个问题 (stackoverflow.com/questions/27626253/…) 上发现了一种解决方法可能是“退出时删除浏览历史记录”。将尝试实施
-
所以你是说 DoEvents 部分很慢?如果您在等待 DoEvents 而不是在浏览器上等待 VBA。您还可以打开 3 个单独的浏览器,这样您就不必从一个浏览器来回导航 9 次。
-
如果您的工作代码只需要改进,那么您可能在这篇文章的错误位置。 Code Review 是他们处理现有/工作代码的地方,并在速度、安全性、可持续性和寿命方面尽最大努力改进它。试一试。他们很好!
-
你试过用 XHR like this 代替 IE 吗?
-
@omegastripes 不,我没有。会尝试 !!谢谢!
标签: regex vba excel internet-explorer web-scraping