Webbrowser 在web項目中的使用

 1  
 2         string htmlstr = string.Empty;  3 [STAThread]  4         public string GetHtmlByWeb(string url)  5  {  6             try
 7  {  8 
 9  RunWithSingleThread(url); 10                 DateTime dtime = DateTime.Now; 11                 double timespan = 0; 12 //等待 頁面加載完畢 並獲取到參數
13                 while (string.IsNullOrWhiteSpace(htmlstr) && timespan < 10) 14  { 15                     DateTime time2 = DateTime.Now; 16                     timespan = (time2 - dtime).TotalSeconds; 17  } 18                 // double lo = DateTime.Now.Subtract(dtime).TotalSeconds;
19  } 20             catch (Exception) 21  { 22               
23  } 24             finally
25  { 26                 if (t != null && t.ThreadState == ThreadState.Running) 27  { 28  t.Abort(); 29  } 30  } 31            
32             return htmlstr; 33  } 34 
35 
36 //線程
37  private Thread t; 38 //異步執行WebBrowser
39         public void RunWithSingleThread(object url) 40  { 41             ParameterizedThreadStart ps = new ParameterizedThreadStart(GetHtmlWithBrowser); 42             t = new Thread(ps); 43             t.IsBackground = true; 44             t.ApartmentState = ApartmentState.STA; 45  t.Start(url); 46  } 47 
48 private WebBrowser wb; 49         private void GetHtmlWithBrowser(object url) 50  { 51             htmlstr = string.Empty; 52 
53             wb = new WebBrowser(); 54             wb.ScriptErrorsSuppressed = true;  //防止腳本異常跳出彈窗
55             wb.ScrollBarsEnabled = true; 56  wb.Navigate(url.ToString()); 57             
58             wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentCompleted); 59             while (wb.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete) 60  { 61                 System.Windows.Forms.Application.DoEvents(); //避免假死,若去掉則可能沒法觸發 DocumentCompleted 事件。
62  } 63 
64  } 65 //獲取內容
66  public void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 67  { 68             htmlstr = wb.Document.Body.InnerHtml; 69 
70         }
相關文章
相關標籤/搜索