运行数据抓取代码时出错91

时间:2017-06-09 16:47:13

标签: excel-vba runtime-error screen-scraping vba excel

我打电话时遇到错误:Datascrape()定义为:

Sub Datascrape()
  Dim count, i As Long
  Dim ie As Object
  count = Sheets("properties-2017-06-05").Cells(1, 10).Value
  Sheets("properties-2017-06-05").Range("D7:E" & count).ClearContents
  For i = 7 To count
    Set ie = CreateObject("internetexplorer.Application")
    ie.navigate Sheets("properties-2017-06-05").Cells(i, 3).Value
    While ie.busy
      DoEvents
    Wend
    'ie.Visible = True
    Application.Wait (Now + TimeValue("00:00:03"))
    Sheets("properties-2017-06-05").Cells(i, 4) = 
    'error happens here
    ie.document.getelementsbyclassname("col-xs-12 viewAllReviews")(0).innertext
    On Error Resume Next
    Sheets("properties-2017-06-05").Cells(i, 5) = 
    ie.document.getelementsbyclassname("APGWBigDialChart widget")(0).getElementsByTagName("text")(1).innertext
    On Error Resume Next
    ie.Quit
  Next
End Sub

在循环的大约3或4次迭代之后,它会抛出Error 91,我不明白为什么。

link to picture

1 个答案:

答案 0 :(得分:0)

当对象求值为Nothing时,将发生运行时错误91,因为您将(0)(索引)链接到可能不返回有效对象/集合的表达式。

使用此表达式,

ie.document.getelementsbyclassname("col-xs-12 viewAllReviews")(0).innertext

如果getElementsByClassName方法返回一个空集合,那么尝试索引该集合0将引发91错误。

基本上,您的代码是以这样的方式编写的,即假定此方法调用将始终导致长度为> = 1的集合。

为什么不呢?

您的等待循环和Application.Wait可能不够。考虑修改等待循环:

While ie.busy and not ie.ReadyState = 4
    DoEvents
Wend

可能足以解决问题。我还建议将循环中的ie实例化移到之外,没有理由在循环内重复创建ie对象。

肯定会避免错误,并建议调试的位置/位置:

Sub Datascrape()
Dim count as Long, i As Long
Dim ie As Object
Dim ws as Worksheet

Set ws = Sheets("properties-2017-06-05")
Set ie = CreateObject("internetexplorer.Application")

count = ws.Cells(1, 10).Value
ws.Range("D7:E" & count).ClearContents
For i = 7 To count
    ie.navigate ws.Cells(i, 3).Value
    While ie.busy and not ie.ReadyState = 4
        DoEvents
    Wend
    Application.Wait (Now + TimeValue("00:00:03"))  '## This line probably isn't needed
    Dim ele
    Set ele = ie.document.getelementsbyclassname("col-xs-12 viewAllReviews")
    If ele Is Nothing Then
        MsgBox "Class name 'col-xs-12 viewAllReviews' isn't found!"
        ws.Cells(i, 4) = "NOT FOUND"  '## Breakpoint here if needed to debug
    Else:
        ws.Cells(i, 4) = ele(0).innerText
    End If
    On Error Resume Next
    ws.Cells(i, 5) = _
        ie.document.getelementsbyclassname("APGWBigDialChart widget")(0).getElementsByTagName("text")(1).innertext
    On Error GoTo 0
Next
ie.Quit
End Sub

注意:为了提供更具体的指导,您需要提供有助于重现错误的示例输入。

此外,还有关于错误处理的说明

您的循环中有On Error Resume Next表达式,后跟On Error Resume Next。这几乎肯定不是你想要的。通常,它就像:

On Error Resume Next
 << expression(s) >>
On Error GoTo 0

你有:

On Error Resume Next
 << expression(s) >>
On Error Resume Next

除非您实际拥有前者,否则您的循环似乎不会可能引发错误,除非第一次迭代。 GoTo 0恢复正常的错误处理,Resume Next只是意味着“假装错误未发生,即使它们是”。它不提供可用于排除故障的诊断信息。根据经验,应避免这种情况(少数例外)。你所做的是基本上允许迭代1上的错误,但是抑制所有其他错误。