繁体   English   中英

如何使用WebBrowser控件读取网页

[英]How Can Read Web Page Using WebBrowser control

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循环”进行了更多操作,则一个网址每次都不会调用DocumentCompleted事件,请提出建议。

从评论:

..但不支持异步或等待,我认为我使用vs2010进行了测试,并且我已经安装了Nuget,但仍然要找到异步关键字,请帮助

如果您不能使用async/await ,那么您将不能使用for循环进行异步WebBrowser导航,除非使用DoEvents弃用了hacks。 使用状态模式 ,这就是C#5.0编译器在后台为async/await

另外,如果你够大胆,可以模拟async/awaityield ,如所描述这里

更新的 ,下面是利用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" });
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM