Excel VBA:等待Internet Explorer中的JavaScript执行

时间:2012-10-23 11:46:20

标签: excel internet-explorer vba automation

我正在尝试在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对象中评估脚本?

3 个答案:

答案 0 :(得分:0)

我找到了等待页面完成的代码。根据笔记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

答案 1 :(得分:0)

您实际上可以使用ie窗口评估javascript函数。但是你必须设置一个Callback,因为该函数将被评估为异步。

答案 2 :(得分:0)

这篇文章已经很老了,但是由于我已经找到了解决方法,因此我也将对此作答。

仅指向您期望在jQuery脚本运行后存在的内容,使用通过IE自动化运行的JavaScript触发所需的事件,然后执行循环以等待所需的内容出现。

'This will trigger the jQuery event.
Doc.parentWindow.execScript "$('#optionbox').trigger('change')"

'This is the code that will make you wait. It's surprisingly efficient
Do While InStrB(Doc.getElementById("optionbox").innerHTML, "<desired html tag>") = 0
    DoEvents
Loop