【问题标题】:How Can Read Web Page Using WebBrowser control如何使用 WebBrowser 控件读取网页
【发布时间】:2014-03-23 07:34:48
【问题描述】:
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”事件中读取网页,但如果我是 对多个 URL 使用“For 循环”它不会每次都调用 DocumentCompleted 事件如果有什么好主意,请提出建议。

【问题讨论】:

标签: c# webbrowser-control


【解决方案1】:

来自评论:

.. 但不支持异步或等待我认为我正在使用 vs2010 并且我 已经安装了 Nuget 但仍然在寻找 async 关键字,请 帮助

如果您不能使用async/await,那么您就不能使用for 循环进行异步WebBrowser 导航,除非使用DoEvents 来使用已弃用的hack。使用 state pattern,这是 C# 5.0 编译器在后台为 async/await 生成的内容。

或者,如果您有足够的冒险精神,您可以使用yield 模拟async/await,如here 所述。

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

【讨论】:

  • 你能解释一下你的代码吗?特别是我不清楚代表和 IEnumerator 是如何工作的。
  • @AbdurRahim,这个问题专门针对WebBrowser。如果您需要了解编译器生成的基于IEnumerator 的状态机和yield 如何一般工作,请查看:blogs.msdn.com/b/shawnhar/archive/2010/10/01/…。您可能还想将此作为一个单独的问题提出。
猜你喜欢
  • 2010-10-18
  • 1970-01-01
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
相关资源
最近更新 更多