2012-10-23 114 views
1

我想在Excel VBA中做一些網頁抓取。這是我遇到的麻煩的部分代碼:Excel VBA:在Internet Explorer中等待JavaScript執行

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對象中直接評估腳本?

+0

是否有腳本運行的結果,您可以檢查?頁面元素是否被創建,或者某些表單值是否被填充? AFAIK沒有「scriptfinishedrunning」事件,因此您必須檢查腳本的輸出或結果。如果不清楚腳本的功能,很難多說些什麼。 –

+0

謝謝蒂姆,這是一個好主意,雖然我覺得自己有點愚蠢。我只是檢查SearchPage.Initialize是否仍在體內。 –

回答

0

我發現代碼沒有等待頁面完成。根據筆記here,它需要Microsoft Internet控制作爲您的代碼中的參考。

代碼複製在這裏,以防萬一鏈接死:

'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 
+0

謝謝你的回答肖恩。不幸的是,這不起作用,因爲當READYSTATE更改爲READYSTATE_COMPLETE(= 4)時,DocumentComplete事件觸發,這正是我在解決方案中所做的。來源:[鏈接](http://msdn.microsoft.com/en-us/library/aa768329(v = vs.85).aspx) –

+0

此解決方案也僅適用於瀏覽器的可見性設置設置爲true ,這在我的情況下是不可接受的。 –

0

實際上,你可以評估與IE窗口的JavaScript功能。但是你必須設置回調函數,因爲函數將被評估爲異步。