gpt4 book ai didi

Excel VBA : Wait for JavaScript execution in Internet Explorer

转载 作者:行者123 更新时间:2023-12-02 17:34:24 24 4
gpt4 key购买 nike

我正在尝试在 Excel VBA 中进行一些网页抓取。这是我遇到问题的代码部分:

IE.Navigate URL
Do
DoEvents
Loop While IE.ReadyState <> 4 Or IE.Busy = True
Set doc = IE.document

运行此 doc 后,其中包含仍包含未执行的 JavasScript 的 html。这是尚未执行的脚本的签名:

<SCRIPT type=text/javascript>
goosSearchPage.Initialize(...)...;
</SCRIPT>

我可以通过执行 Application.Wait(Now + TimeValue(x)) 来等待执行,但这确实不能令人满意,因为脚本执行所需的时间是相当可变的,具体取决于输入。

有没有办法等待脚本完成评估或直接在 doc 对象中评估脚本?

最佳答案

我发现代码确实等待页面完成。根据注释here ,它需要 Microsoft Internet Controls 作为代码中的引用。

此处复制代码,以防链接失效:

'Following code goes into a sheet or thisworkbook class object module
Option Explicit

'Requires Microsoft Internet Controls Reference Library
Dim WithEvents ie As InternetExplorer
Sub start_here()
Set ie = New InternetExplorer
'Here I wanted to show the progress, so setting ie visible
ie.Visible = True
'First URL to go, next actions will be executed in
'Webbrowser event sub procedure - DocumentComplete
ie.Navigate "www.google.com"
End Sub
Private Sub ie_DocumentComplete(ByVal pDisp As Object, URL As Variant)
'pDisp is returned explorer object in this event
'pDisp.Document is HTMLDocument control that you can use
'Following is a choice to follow,
'since there is no do-loop, we have to know where we are by using some reference
'for example I do check the URL and do the actions according to visited URL

'In this sample, we use google entry page, set search terms, click on search button
'and navigate to first found URL
'First condition; after search is made
'Second condition; search just begins
If InStr(1, URL, "www.google.com/search?") > 0 Then
'Open the first returned page
ie.Navigate pDisp.Document.getelementsbytagname("ol")(0).Children(0).getelementsbytagname("a")(0).href
ElseIf InStr(1, URL, "www.google.com") > 0 Then
pDisp.Document.getelementsbyname("q")(0).Value = "VB WebBrowser DocumentComplete Event"
pDisp.Document.getelementsbyname("btnG")(0).Click
End If
End Sub

关于Excel VBA : Wait for JavaScript execution in Internet Explorer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13029708/

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