gpt4 book ai didi

excel - 内联网上的网页抓取

转载 作者:行者123 更新时间:2023-12-03 01:02:20 25 4
gpt4 key购买 nike

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

问题:

出现以下错误:

Run-time error '91':
object variable or with block variable not set

它发生在:

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 进程。

关于excel - 内联网上的网页抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27865219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com