Webbrowser 在web项目中的使用

2018/03/06 15:20
阅读数 26
 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         }

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部