HTMLAgilityPack - 您需要将UseIdAttribute属性设置为true才能启用此功能

use*_*317 8 c# html-agility-pack

我正在尝试将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)
Run Code Online (Sandbox Code Playgroud)

我试过版本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");
Run Code Online (Sandbox Code Playgroud)

这也不起作用,

    HtmlWeb web = new HtmlWeb();
    HtmlDocument doc = new HtmlDocument { OptionUseIdAttribute = true };
    doc = web.Load(url);
    HtmlNode table = doc.GetElementbyId("tblThreads");
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?谢谢.

Ben*_*ith 4

首先,我在 1.4.0 HAP Dll 上使用ILSpy 。我导航到 HtmlDocument 类,可以看到 GetElementById 方法如下所示:

// HtmlAgilityPack.HtmlDocument
/// <summary>
/// Gets the HTML node with the specified 'id' attribute value.
/// </summary>
/// <param name="id">The attribute id to match. May not be null.</param>
/// <returns>The HTML node with the matching id or null if not found.</returns>
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;
}
Run Code Online (Sandbox Code Playgroud)

然后我让 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");
Run Code Online (Sandbox Code Playgroud)

这种方法确保调用“HtmlDocument.Load(TextReader)”,并且在该代码中我可以看到 _nodesid 肯定会被分配,所以这种方法可能(我没有编译我建议的代码)工作。