private void button1_Click(object sender, EventArgs e)
{
string url = urlTextBox.Text;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
richTextBox1.Text = sr.ReadToEnd();
webBrowser1.DocumentText = richTextBox1.Text;
HtmlElement htmlElement = webBrowser1.Document.GetElementById("name");
string data = htmlElement.InnerText;
label1.Text = data;
sr.Close();
}
我想读取 php 文件的 id 元素内的一些文本,但在这一行有一点问题
string data = htmlElement.InnerText;
我从 Visual Studio 2010 收到一些警告
NullReferenceExpection was unhandled
Object reference not set to an instance of an object.
有人可以帮我吗?谢谢:)
最佳答案
我认为这里的问题可能是 WebBrowser
控件异步加载文档。因此,当您尝试立即访问 webBrowser1.Document
时,就会出现问题。
DocumentText
属性:
If you set the value of this property and then immediately retrieve it again, the value retrieved may be different than the value set if the WebBrowser control has not had time to load the new content. You can retrieve the new value in a DocumentCompleted event handler. Alternatively, you can block the thread until the document is loaded by calling the Thread.Sleep method in a loop until the DocumentText property returns the value that you originally set it to.
另请参阅DocumentCompleted事件。
关于c# - 如何在 C# 中从 StreamReader 获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11179571/