2013-07-17 63 views
0

我正在嘗試獲取單擊按鈕後得到的網頁的源代碼。如何在代碼中模擬網頁按鈕點擊後獲取源代碼

我可以點擊位於網頁上的按鈕。

webBrowser1.Navigate(url); 
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) 
{ 
    Application.DoEvents(); 
}    
webBrowser1.Document.GetElementById("downloadButton").InvokeMember("click"); 

此後出現一個新窗口。點擊後可能會出現這個新窗口的源代碼。

回答

0

哈克方法是:

  1. 附加的事件處理程序的按鈕的的「onClick」事件。
  2. 然後,一旦事件被觸發,請使用Microsoft Internet Controls(SHDocVw)類型庫以獲取在IE中打開的最後一個URL。
  3. 最後,導航到URL,一旦加載文檔,從webBrowser1.DocumentText屬性獲取文檔的來源。

在項目中,添加到Microsoft Internet控制類型庫的引用(你會發現它在COM標籤)。添加在你的文件的頂部:

using SHDocVw; 

代碼:

webBrowser1.Navigate(url); 
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) 
{ 
    Application.DoEvents(); 
} 

// assign the button to a variable 
var button = webBrowser1.Document.GetElementById("downloadButton"); 

// attach an event handler for the 'onclick' event of the button 
button.AttachEventHandler("onclick", (a, b) => 
{ 
    // use the Microsoft Internet Controls COM library 
    var shellWindows = new SHDocVw.ShellWindows(); 

    // get the location of the last window in the collection 
    var newLocation = shellWindows.Cast<SHDocVw.InternetExplorer>() 
     .Last().LocationURL; 

    // navigate to the newLocation 
    webBrowser1.Navigate(newLocation); 
    while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) 
    { 
     Application.DoEvents(); 
    } 

    // get the document's source 
    var source = webBrowser1.DocumentText; 
}); 

button.InvokeMember("click"); 
+0

我通過上面的代碼運行了一個腳本錯誤。說道:!此頁面上的腳本發生錯誤。 – Manish