如何在加载时间过长时跳过部分代码

时间:2014-05-29 13:24:14

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

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

我正在运行一个webscraper并且通常它运行良好,但我经常遇到“运行时错误”。如果加载网站所花费的时间太长,我想通过跳过特定的任务(在我的情况下在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中加载网页的帖子,但找不到我可以实现的网页(新手上班)。

希望这提供澄清

1 个答案:

答案 0 :(得分:2)

我想您可能想重新考虑如何使用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循环以将其考虑在内

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“,具体取决于代码的其余部分的结构。