【问题标题】:Using the DocumentComplete event C#使用 DocumentComplete 事件 C#
【发布时间】:2012-12-20 16:00:57
【问题描述】:

我第一次开始在 C# 中使用 WebBrowser 控件。我正在尝试做一些非常简单的事情:在文本框中写一个文本,然后单击一个按钮进行登录。

WebContest wc_class = new WebContest();
...

 wc_class.wbThread1.Navigate("http://www.mysite.com");
        while (wc_class.wbThread1.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents();

这里登录页面的ReadyState完美运行,接下来继续在文本框中写入文本然后单击按钮

wc_class.wbThread1.Document.GetElementById("field_email").SetAttribute("value", tbLogin.Text);
wc_class.wbThread1.Document.GetElementById("field_password").SetAttribute("value", tbPassword.Text);
wc_class.wbThread1.Document.GetElementById("field_remember").InvokeMember("click");
wc_class.wbThread1.Document.GetElementById("hook_FormButton_button_go").InvokeMember("click");

这一次,登录后我需要从页面中提取链接。 做这样的事情:

...
foreach (HtmlElement link in wc_class.wbThread1.Document.Links)
            {
                string href = link.GetAttribute("HREF");
                string fileName = "links.txt";
                using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write))
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine(href);
                } 

麻烦在于期待 DocumentComplete 事件。登录后的页面没有等待加载。为什么?点击登录按钮后如何查看页面的ReadyState?

以及如何为页面导航中的所有事件执行此操作?

【问题讨论】:

    标签: c# navigation browser


    【解决方案1】:

    我遇到了这个问题并使用计时器解决了它。在InvokeMember("click"); 之后,我启动了一个计时器几秒钟,然后在计时器滴答声中检查ReadyState。如果完成 - 停止计时器,否则将再次触发。

    System.Windows.Forms.Timer yesTimer;
    yesTimer.Interval = 2000;
    
    public Main()
    {
      webBrowser1.Navigate("http://www.mysite.com");
      yesTimer.Start();
    }
    
      private void yesTimer_Tick(object sender, EventArgs e)
      {
         if (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
         {
            return;
         }
    
         yesTimer.Stop();
         //do here whatever you want then webBrowser1 is completed
      }
    

    【讨论】:

    • 但是如果应用程序是为大众编写的会发生什么?我们都有不同的互联网,在某些情况下您的方法可能不合适。
    • @Johnny 为什么不呢?正如我所说,计时器将每隔 2 秒触发一次,直到 WebBrowserReadyState == Complete
    • okey,你能为这个问题做一个完整的例子吗?我测试了一些这样的:this.wb.wbThread1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.wbThread1_DocumentCompleted);播种效果不好。
    猜你喜欢
    • 2014-05-13
    • 2012-08-25
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    相关资源
    最近更新 更多