【问题标题】:WebBrowser loading page exceptionWebBrowser 加载页面异常
【发布时间】:2015-05-23 20:47:23
【问题描述】:

我有简单的代码,可以加载页面并通过 id 获取元素。我正在使用标准组件WebBrowser webWebBrowser = new WebBrowser(); 我的问题是加载页面。

错误代码:

webWebBrowser.Navigate(url);
while (webWebBrowser.ReadyState != WebBrowserReadyState.Complete)
{
    Application.DoEvents();
}
var links = webWebBrowser.Document.GetElementById("n6");
String tmp = links.InnerText;

我在网上遇到错误:

var links = webWebBrowser.Document.GetElementById("n6");

错误是:

发生了“System.NullReferenceException”类型的未处理异常。

但是,如果我将MessageBox 添加到代码中,它就会起作用(单击按钮后)。为什么?

无错误代码:

webWebBrowser.Navigate(url);
while (webWebBrowser.ReadyState != WebBrowserReadyState.Complete)
{
    Application.DoEvents();
}
MessageBox.Show("loaded");
var links = webWebBrowser.Document.GetElementById("n6");
String tmp = links.InnerText;

【问题讨论】:

  • 似乎 MessageBox.Show 在 readyState.Complete 和 Document.GetElementById 之间添加了一个延迟,添加一个短暂的延迟而不是使用 MessageBox,看看是否能解决问题。你确定空指针异常是在该行而不是它后面的链接可能为空的行。
  • @faljbour:我尝试使用睡眠啤酒对我没有帮助。确认消息框后加载页面。

标签: c# twebbrowser


【解决方案1】:

您尝试在文档完全加载之前阅读文档的内容(显示 MessageBox 可以让您的 WebBrowser 有一些时间来完全加载内容)。

您应该使用DocumentCompleted 事件

webBrowser.DocumentCompleted += (s, e) =>
{
    var links = webWebBrowser.Document.GetElementById("n6");
    String tmp = links.InnerText;
};

webWebBrowser.Navigate(url);

【讨论】:

    猜你喜欢
    • 2014-06-18
    • 2011-02-16
    • 2011-05-12
    • 1970-01-01
    • 2017-02-02
    • 2012-09-05
    • 1970-01-01
    • 2012-05-22
    • 2014-06-24
    相关资源
    最近更新 更多