为什么HTML Agility Pack HtmlDocument.DocumentNode为空?
我正在使用此代码来更改HTML流的href属性。
首先我使用以下代码下载完整的html页面:( URL是网页地址)
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL); HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); Stream s = myHttpWebResponse.GetResponseStream();
然后我处理这个:
HtmlDocument doc = new HtmlDocument(); doc.Load(s); foreach (HtmlNode link in doc.DocumentNode.SelectNodes("/a")) { string att = link.Attributes["href"].Value; link.Attributes["href"].Value = "http://ahmadalli.somee.com/default.aspx?url=" + att; } doc.Save(s);
s
是html流。
但我有一个例外,说doc.DocumentNode
为空!
我尝试了很多网站,但doc.DocumentNode
为null
这对我有用。
using(WebClient client = new WebClient()) { client.Encoding = System.Text.Encoding.UTF8; var doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(client.DownloadString("http://www.google.com?q=stackoverflow")); foreach (var href in doc.DocumentNode.Descendants("a").Select(x => x.Attributes["href"])) { if (href == null) continue; href.Value = "http://ahmadalli.somee.com/default.aspx?url=" + HttpUtility.UrlEncode(href.Value); } StringWriter writer = new StringWriter(); doc.Save(writer); var finalHtml = writer.ToString(); }
另请参阅HttpUtility.UrlEncode
以便能够正确获取url。 否则,原始URL中的某些参数可能会导致问题。
使用HttpUtility.UrlDecode
进行解码。
尝试使用//a
而不是/a
。
在XPath中,这基本上意味着给我文档中的所有链接 ,而不是给我文档根目录中的所有链接 。
更新:
以下代码工作正常:
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://google.com"); var myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); var s = myHttpWebResponse.GetResponseStream(); var doc = new HtmlDocument(); doc.Load(s); foreach (var link in doc.DocumentNode.SelectNodes("//a")) { var att = link.Attributes["href"].Value; link.Attributes["href"].Value = "http://ahmadalli.somee.com/default.aspx?url=" + att; Console.WriteLine(link.Attributes["href"].Value); }
以下是您的答案: HTML Agility Pack Null参考 。
尝试使用以下代码:
HtmlDocument htmlDoc = new HtmlDocument { OptionAddDebuggingAttributes = false, OptionAutoCloseOnEnd = true, OptionFixNestedTags = true, OptionReadEncoding = true }; try { using (Stream reader = myHttpWebResponse.GetResponseStream()) { reader.Seek(0, SeekOrigin.Begin); htmlDoc.Load(reader, true); } HtmlNode node = htmlDoc.DocumentNode; if (node != null) { foreach (var href in doc.DocumentNode.Descendants("a").Select(x =>x.Attributes["href"])) { href.Value = "http://ahmadalli.somee.com/default.aspx?url=" +HttpUtility.UrlEncode(href.Value); } } } catch { }
我使用的是HtmlAgility包版本:1.4.0
解决了你的问题? 如果不是,请发表评论。 其他标记为答案。
锚标记引用是错误转义的字符串:
...doc.DocumentNode.SelectNodes("/a") //incorrect ...doc.DocumentNode.SelectNodes("//a") //correct ...doc.DocumentNode.SelectNodes(@"/a") //also correct
原始代码无法选择任何节点并评估为null; 这应该被检查,以防止失败,比如说,根本没有链接的文件(不过不太可能:)
var anchors = doc.DocumentNode.SelectNodes("//a"); if (anchors != null) { foreach (HtmlNode link in anchors) { /*do stuff*/ } }