【问题标题】:How to skip a part of code when it takes too long to load加载时间过长时如何跳过部分代码
【发布时间】:2014-05-30 01:20:31
【问题描述】:

有人回答了我的问题for Java,我基本上是在@enderland here 提供的先前答案的基础上构建的。

我正在运行一个网络爬虫,通常它运行良好,但我经常遇到“运行时错误”。如果加载网站的时间太长,我想通过跳过特定任务(在我的情况下在 Google 上加载专利页面)来避免这种情况。

我认为我需要一个简单的If Then,但我不知道使用哪个函数来控制时间的流逝。

有什么建议吗?

目前我运行以下内容:

Function citecount(patent_number As String, patent As String, ccount As Integer, info As String)

patent = ""
ccount = 0
If patent_number = "" Then Exit Function

the_start:


Set ie = CreateObject("InternetExplorer.Application")

    ie.Top = 0
    ie.Left = 0
    ie.Width = 800
    ie.Height = 600
    ie.Visible = False 'If False we won't see the window navigation

On Error Resume Next
     ie.Navigate ("http://www.google.com/patents/US" & patent_number & "?")
        Sleep (600)
      Do
        DoEvents
            If Err.Number <> 0 Then
                ie.Quit
                Set ie = Nothing
                GoTo the_start:
            End If
           Sleep (1250)

        Loop Until ie.ReadyState = 4

Sleep() 被定义为:

Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

我面临的主要错误描述为here。这是Run-time error '2147467259 (80004005) automation error, unspecified error。此外,在我添加Sleep() 命令之前,我还得到了Microsoft Excel is waiting for another Application to complete an on OLE action,但自从添加Sleep() 命令后就没有回来了。

最后我得到一个 IE 警告:

Stop running this script? A Script on thispage is causing your web browser to run slowly. If it continues to run your computer might become unresponsive

我认为这些都是由于网页花费大量时间下载我不需要的图像而引起的。我阅读了一些关于直接在 html 中加载网页的帖子,但在 SO 上没有图像,但找不到我可以实现的帖子(工作中的新手)。

希望这能提供澄清

【问题讨论】:

  • 什么运行时错误?另外,您可以发布更多代码吗?您当前的 If Err.Number... 块(如果仅此而已)永远不会捕获错误,除非您在其前面的某处有 On Error Resume Next

标签: vba internet-explorer if-statement time scrape


【解决方案1】:

我认为您可能需要重新考虑如何使用 IE/您的代码来解决一般问题。如果您真的只是想使用超时来跳过 IE 调用,您可以执行以下操作。

使用此函数获取两个日期之间经过的时间:

Function ElapsedTimeInSeconds(endTime As Date, startTime As Date) As Long
    ' Calculate the time interval in seconds
    If endTime > startTime Then
        ElapsedTimeInSeconds = DateDiff("s", startTime, endTime)
    Else
        ElapsedTimeInSeconds = 0 ' cannot have negative elapsed time...
    End If
End Function

更改您的 do Loop 以考虑到这一点

Dim startTime As Date: startTime = Now
Dim timeout As Long: timeout = 5  'seconds
Do
    DoEvents
    If Err.Number <> 0 Then
        ie.Quit
        Set ie = Nothing
        GoTo the_start:
    End If
    Sleep (1250)
Loop Until ie.ReadyState = 4 Or ElapsedTimeInSeconds(Now, startTime) > timeout

或者您可能想使用 ElapsTimeInSeconds() 函数返回“ _start”,具体取决于其余代码的结构。

【讨论】:

  • 感谢 Armen,我实施了您的解决方案,效果非常好,尤其是当我意识到我可以通过一些高级设置阻止图像显示在 IE 中时。但是,我仍然收到我之前描述的运行时错误 (stackoverflow.com/questions/23818004/…),它基本上使我无法在一夜之间运行代码,因为它每 10 到 15 分钟就会失败一次。您提到了解决我的问题的不同方法。您能否就如何更有效地工作提供任何线索?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-21
  • 1970-01-01
  • 2012-08-23
  • 2016-06-20
  • 2016-02-17
  • 1970-01-01
相关资源
最近更新 更多