内联网网页抓取



我编写了一个VBA代码来从我公司的内部网抓取数据。

问题:

出现以下错误:

运行时错误"91":
对象变量或未设置块变量

它发生在:

myPoints = Trim(Doc.getElementsByName("price")(0).getAttribute("value"))

当我调试它并逐行运行时,它可以检索所有值。

输入和输出:

我在 B 列上输入多个产品 ID,并在 C 列上检索数据:
列 B = 产品 ID
C 列 = 价格

.HTML:

<td id="myPower_val_9" style="visibility: visible;">
    <input type="text" disabled="disabled" value="300" name="price"></input>
</td>

VBA:

Sub Button1_Click()
Dim ie As Object
Dim r As Integer
Dim myPoints As String
Dim Doc As HTMLDocument
Set ie = New InternetExplorerMedium
For r = 2 To Range("B65535").End(xlUp).Row
    With ie
        .Visible = 0
        .navigate "www.example.com/product/" & Cells(r, "B").Value
        Do Until .readyState = 4
            DoEvents
        Loop
    End With
    Set Doc = ie.document
    myPoints = Trim(Doc.getElementsByName("price")(0).getAttribute("value"))
    Cells(r, "C").Value = myPoints
Next r
End Sub

我是否错过了错误处理程序?

在访问任何元素之前,您需要等待文档完全呈现并且 DOM 可用。 ie.ReadyState页面连接并开始加载后更改为READYSTATE_COMPLETE。代码在调试时正常工作的原因是,在开始使用调试器所需的几秒钟内,页面完成加载。

With ie
   .Visible = True
   .Navigate "www.example.com/product/" & Cells(r, "B").Value
   Do Until .ReadyState = READYSTATE_COMPLETE
       DoEvents
   Loop
   Do Until .Document.ReadyState = "complete"
       DoEvents
   Loop
End With

我还建议您至少在开发时使ie窗口可见。完成功能并调试后,可以使窗口不可见。请记住,如果您在代码完成后忘记关闭不可见的IE窗口,则用户最终将获得失控的iexplore.exe进程。

如果只想忽略错误并继续下一次迭代,请使用以下修改后的代码:

Sub Button1_Click()
Dim ie As Object
Dim r As Integer
Dim myPoints As String
Dim Doc As HTMLDocument

Set ie = New InternetExplorerMedium

For r = 2 To Range("B65535").End(xlUp).Row
With ie
  .Visible = 0
  .navigate "www.example.com/product/" & Cells(r, "B").Value
   Do Until .readyState = 4
   DoEvents
   Loop
End With

 Set Doc = ie.document

 'Edit:
 myPoints = ""
 On Error Resume Next
 myPoints = Trim(Doc.getElementsByName("price")(0).getAttribute("value"))
 On Error Goto 0
 Cells(r, "C").Value = myPoints
Next r
End Sub

你也可以循环直到设置元素(也添加一个超时子句)

Dim a As Object
Do
    DoEvents
    On Error Resume Next 
    Set a = Doc.getElementsByName("price")
    On Error GoTo 0
Loop While a Is Nothing 

相关内容

  • 没有找到相关文章

最新更新