HTMLAgilityPack - You need to set UseIdAttribute property to true to enable this feature

只谈情不闲聊 提交于 2019-12-05 02:59:11

First I used ILSpy on the 1.4.0 HAP Dll. I navigated to the HtmlDocument class and could see that the GetElementById method looks like this:

// 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;
}

I then got ILSpy to analyze "_nodesid", because in your case for some reason it is not being set. "HtmlDocument.DetectEncoding(TextReader)" and "HtmlDocument.Load(TextReader)" assigns value to "_nodesid".

Hence you could try an alternative method to read the content from the URL whereby the "_nodesid" value will be definitely assigned e.g.

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");

This approach ensures that "HtmlDocument.Load(TextReader)" is called, and in that code I can see that _nodesid will definitely get assigned, so this approach may (I haven't compiled the code I've suggested) work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!