HTMLAgilityPack – 您需要将UseIdAttribute属性设置为true才能启用此function
我正在尝试将HTMLAgilityPack与VS2008 / .Net 3.5一起使用。 即使我将OptionUseIdAttribute设置为true,我也会收到此错误,但默认情况下它应该为true。
Error Message: You need to set UseIdAttribute property to true to enable this feature Stack Trace: at HtmlAgilityPack.HtmlDocument.GetElementbyId(String id)
我尝试了1.4.6和1.4.0版,但都没有用。
版本1.4.6 – Net20 / HtmlAgilityPack.dll
版本1.4.0 – Net20 / HtmlAgilityPack.dll
这是代码,
HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load(url); HtmlNode table = doc.GetElementbyId("tblThreads");
这也不起作用,
HtmlWeb web = new HtmlWeb(); HtmlDocument doc = new HtmlDocument { OptionUseIdAttribute = true }; doc = web.Load(url); HtmlNode table = doc.GetElementbyId("tblThreads");
我该如何解决这个问题? 谢谢。
首先我在1.4.0 HAP Dll上使用了ILSpy 。 我导航到HtmlDocument类,可以看到GetElementById方法如下所示:
// HtmlAgilityPack.HtmlDocument /// /// Gets the HTML node with the specified 'id' attribute value. /// /// The attribute id to match. May not be null. /// The HTML node with the matching id or null if not found. public HtmlNode GetElementbyId(string id) { if (id == null) { throw new ArgumentNullException("id"); } if (this._nodesid == null) { throw new Exception(HtmlDocument.HtmlExceptionUseIdAttributeFalse); } return this._nodesid[id.ToLower()] as HtmlNode; }
然后我让ILSpy分析“_nodesid”,因为在你的情况下由于某种原因它没有被设置。 “HtmlDocument.DetectEncoding(TextReader)”和“HtmlDocument.Load(TextReader)”将值赋给“_nodesid”。
因此,您可以尝试另一种方法来从URL中读取内容,从而明确分配“_nodesid”值,例如
var doc = new HtmlDocument(); var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; using (var response = (HttpWebResponse)request.GetResponse()) { using (var stream = response.GetResponseStream()) { doc.Load(stream); } } var table = doc.GetElementbyId("tblThreads");
这种方法确保调用“HtmlDocument.Load(TextReader)”,并且在该代码中我可以看到_nodesid肯定会被分配,所以这种方法可能 (我没有编译我建议的代码)工作。