2014-12-03 63 views
0

我有一個C#應用程序在WebBrowser中自動填寫和提交表單,然後在表單提交併在服務器上處理後返回我DocumentText,但我試過這個代碼,但我在表單提交之前獲得DocumentText在表單提交後獲取webBrowser的DocumentText

private String afterform() 
    { 
     String toreturnstring = ""; 
     while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) 
     { 
      Application.DoEvents(); 
     } 
     HtmlElement theform= webBrowser1.Document.GetElementById("theform"); 
     theform.InvokeMember("Submit"); 


     while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) 
     { 
      Application.DoEvents(); 
     } 
     toreturnstring = webBrowser1.DocumentText; 
     return toreturnstring; 

    } 

注:我看到返回toreturnstring後的表格目標頁面已經打開。

回答

1

出現這種情況的,因爲你太很快得到DocumentText。當WebBrowsers狀態返回到完成時,不一定設置DocumentText。

根據MSDN:

如果設置此屬性的值,然後立即取回 一遍,檢索到的價值可能比設定的值,如果 WebBrowser控件還沒有來得及不同加載新內容。您可以在DocumentCompleted事件處理程序中檢索新值,您可以使用 。 或者,直到該文件是通過調用一個循環,直到DocumentText 屬性的Thread.Sleep方法加載 返回您最初設置的值,你可以阻塞線程。

雖然在這種情況下我們不是直接設置DocumentText的值,但我仍然想做一個快速測試,以查看頁面導航中是否發生更改。在測試之後,注意到在調用DocumentCompleted事件處理程序時DocumentTest仍未設置。

我創造了另一個事件的頁面網址更改後(按鈕)能抽空發生。然後我檢查了DocumentText並將其更改爲新頁面。也嘗試與thread.sleep MSDN建議,它的工作原理。

我希望這會有所幫助。

public string NewDocumentTextForMeToPlayWith{ get; set; } 

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
{ 
    NewDocumentTextForMeToPlayWith = webBrowser1.DocumentText; 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    HtmlElement theform = webBrowser1.Document.GetElementsByTagName("form")[0]; 
    theform.InvokeMember("Submit"); 
    while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) 
    { 
     Application.DoEvents(); 
    } 

    Thread.Sleep(1000); 


}