How Can Read Web Page Using WebBrowser control

2020-01-29 17:19发布

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);

                }

Am Using above mentioned code for reading WebPage at "DocumentCompleted" Event But If I am Using "For loop" for more then one Url It not calling to DocumentCompleted Event everytime Please suggest if any good idea.

1条回答
Fickle 薄情
2楼-- · 2020-01-29 17:57

From the comment:

.. but async or await is not supported i think iam using vs2010 and i already installed Nuget but still iam finding async keyword, please help

If you can't use async/await, then you can't use for loop for asynchronous WebBrowser navigation, unless resorting to deprecated hacks with DoEvents. Use the state pattern, that's what C# 5.0 compiler generates behind the scene for async/await.

Alternatively, if you're adventurous enough, you can simulate async/await with yield, as described here.

Updated, below is another way of exploiting the C# enumerator state machine (compatible with C# 2.0 and later):

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" });
        }
    }
}
查看更多
登录 后发表回答