如何使用WebBrowser控件读取网页

string urlt = webBrowser1.Url.ToString(); Webbrowser1.Navigate("Google.com") HtmlElement elem; if (webBrowser1.Document != null) { HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("HTML"); if (elems.Count == 1) { elem = elems[0]; string pageSource = elem.InnerHtml; if (pageSource == "404" || pageSource == "Inter" || pageSource == "siteblocked") { } else { Ret2.Add("Page.." + "Url..." + urlt); } 

使用上面提到的代码在“DocumentCompleted”事件中阅读WebPage但是如果我使用“For循环”多于一个Url它没有每次调用DocumentCompleted事件请建议是否有任何好主意。

来自评论:

..但async或await不支持我认为iam使用vs2010并且我已经安装了Nuget但仍然iam找到async关键字,请帮助

如果你不能使用async/await ,那么你就不能使用for循环来进行异步WebBrowser导航,除非使用DoEvents弃用黑客。 使用状态模式 ,即C#5.0编译器在async/await的场景后面生成的模式 。

或者,如果您足够冒险,可以使用yield模拟async/await ,如此处所述。

更新 ,下面是另一种利用C#枚举器状态机的方法(与C#2.0及更高版本兼容):

 using System; using System.Collections; using System.Windows.Forms; namespace WindowsForms_22296644 { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } IEnumerable GetNavigator(string[] urls, MethodInvoker next) { WebBrowserDocumentCompletedEventHandler handler = delegate { next(); }; this.webBrowser.DocumentCompleted += handler; try { foreach (var url in urls) { this.webBrowser.Navigate(url); yield return Type.Missing; MessageBox.Show(this.webBrowser.Document.Body.OuterHtml); } } finally { this.webBrowser.DocumentCompleted -= handler; } } void StartNavigation(string[] urls) { IEnumerator enumerator = null; MethodInvoker next = delegate { enumerator.MoveNext(); }; enumerator = GetNavigator(urls, next).GetEnumerator(); next(); } private void Form_Load(object sender, EventArgs e) { StartNavigation(new[] { "http://example.com", "http://example.net", "http://example.org" }); } } }