【问题标题】:Retrieve Html table data after invoking button click from WebBrowser control从 WebBrowser 控件调用按钮单击后检索 Html 表数据
【发布时间】:2016-02-27 18:32:20
【问题描述】:

在尝试以下代码时,我收到空引用错误

private void button1_Click(object sender, EventArgs e)
{
  webBrowser1.Document.GetElementById("textbox1").InnerText = "sometext";
  webBrowser1.Document.GetElementById("textbox2").InnerText = "sometext";  
  webBrowser1.Document.GetElementById("Button1").InvokeMember("click");
  object tb = webBrowser1.Document.GetElementById("Table1").All;
}

没有第 4 行,我的代码运行良好。但是添加了第 4 行我得到了错误。

其实我想保存点击 button1 后生成的表格。 上一页没有 table1,即在单击按钮之前。

【问题讨论】:

    标签: c# winforms webbrowser-control


    【解决方案1】:

    使用以下内容。我认为它会起作用。

            HtmlElement hleGetData = (HtmlElement)hdoc.GetElementById("getButton");
            hleGetData.InvokeMember("click");
            while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
            {
                System.Windows.Forms.Application.DoEvents();
            };
    
            System.Threading.Thread.Sleep(1000);
            System.Windows.Forms.Application.DoEvents();
            System.Windows.Forms.Application.DoEvents();
            System.Windows.Forms.Application.DoEvents();
            System.Windows.Forms.Application.DoEvents();
            System.Windows.Forms.Application.DoEvents();
            System.Windows.Forms.Application.DoEvents();
            System.Windows.Forms.Application.DoEvents();
    

    【讨论】:

      【解决方案2】:

      您的 WebBrowser 的 Document 属性为空,因为浏览器尚未加载页面。您需要处理 WebBrowser 的 DocumentCompleted 事件并访问其中的 HTML 代码。

      private void webbrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
      {
          // access HTML here
      }
      

      【讨论】:

      • 我试过了,但是 webbrowser_DocumentCompleted() 方法永远不会触发
      • 您需要在表单的构造函数中添加webbrowser.DocumentCompleted += webbrowser_DocumentCompleted; 来处理事件。
      • 或者文档中可能没有Table1id的元素。
      • 或者文档中可能没有Table1id的元素。
      • 如果GetElementById返回null,是因为没有找到id。检查 webbrowser.Document.Body.OuterHtml 的值以查看所有 HTML 并确保 id Table1 存在。
      猜你喜欢
      • 2012-07-01
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多