我有一段代码:
string x = textBox1.Text;
string[] list = x.Split(';');
foreach (string u in list)
{
string url = "http://*********/index.php?n=" + u;
webBrowser1.Navigate(url);
webBrowser1.Document.GetElementsByTagName("META");
}我试图将<META>标记输出到消息框中,但是当我测试它时,我总是得到以下错误:
对象引用未设置为对象的实例。
发布于 2012-04-29 00:07:50
您的问题是在文档加载之前访问Document对象--WebBrowser是异步的。只需使用像HTML敏捷包这样的库来解析HTML。
下面是使用HTML获取<meta>标记的方法。(假设是using System.Net;和using HtmlAgilityPack;。)
// Create a WebClient to use to download the string:
using(WebClient wc = new WebClient()) {
// Create a document object
HtmlDocument d = new HtmlDocument();
// Download the content and parse the HTML:
d.LoadHtml(wc.DownloadString("http://stackoverflow.com/questions/10368605/getelementsbytagname-in-c-sharp/10368631#10368631"));
// Loop through all the <meta> tags:
foreach(HtmlNode metaTag in d.DocumentNode.Descendants("meta")) {
// It's a <meta> tag! Do something with it.
}
}发布于 2012-04-29 00:06:08
在文档加载完成之前,您不应该尝试访问它。在DocumentCompleted事件的处理程序中运行该代码。
但马蒂是对的。如果您只需要读取HTML,就不应该使用WebBrowser。只需获取文本并使用HTML解析器解析它。
发布于 2013-06-05 16:41:35
您可以直接从您的WebBrowser控件中检索元标记和任何其他HTML元素,不需要或其他组件。
就像Mark说的,先等待DocumentCompleted事件:
webBrowser.DocumentCompleted += WebBrowser_DocumentCompleted;然后,您可以从HTML文档中捕获任何元素和内容。以下代码获取标题和元描述:
private void WebBrowser_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
System.Windows.Forms.WebBrowser browser = sender as System.Windows.Forms.WebBrowser;
string title = browser.Document.Title;
string description = String.Empty;
foreach (HtmlElement meta in browser.Document.GetElementsByTagName("META"))
{
if (meta.Name.ToLower() == "description")
{
description = meta.GetAttribute("content");
}
}
}https://stackoverflow.com/questions/10368605
复制相似问题