码迷,mamicode.com
首页 > Web开发 > 详细

Webbrowser 在web项目中的使用

时间:2018-03-06 15:36:19      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:执行   ready   style   finally   htm   nbsp   time   div   public   

 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         }

 

Webbrowser 在web项目中的使用

标签:执行   ready   style   finally   htm   nbsp   time   div   public   

原文地址:https://www.cnblogs.com/dxqNet/p/8514520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!