【问题标题】:HtmlAgilityPack cant get string indexerHtmlAgilityPack 无法获取字符串索引器
【发布时间】:2026-01-15 06:10:02
【问题描述】:

我想使用 HTML Agility Pack 解析 HTML

当我用 int 搜索索引时,我得到了结果。

HtmlWeb htmlWeb = new HtmlWeb();
HtmlDocument htmlDocument = htmlWeb.Load("http://www.timeanddate.com/worldclock/georgia/tbilisi");

var s1 = htmlDocument.DocumentNode.Descendants().Where(x => x.HasAttributes && x.Attributes[0].Value == "ct");

但是当我想用字符串索引器搜索属性时,我得到了一个例外。

var s2 = htmlDocument.DocumentNode.Descendants().Where(a => a.HasAttributes && a.Attributes["id"].Value == "ct");

当我不使用 LINQ 并使用谓词委托时,一切正常。

Predicate<HtmlNode> pred = new Predicate<HtmlNode>(forpred);
List<HtmlNode> ss = htmlDocument.DocumentNode.Descendants().ToList().FindAll(pred);
public static bool forpred(HtmlNode node)
{
   if (node.HasAttributes)
   {    
      foreach (HtmlAttribute atribute in node.Attributes)
      {
         if (atribute.Name == "id" && atribute.Value == "ct")
         {
             return true;
         }
      }
   }
   return false;
}


//s1.ToList()[0].InnerHtml
//s2.ToList()[0].InnerHtml 
//ss[0].InnerHtml 

【问题讨论】:

    标签: c# html-parsing html-agility-pack


    【解决方案1】:

    因为有些 span 有属性但没有 id。你的代码可以是这样的:

    var s2 = htmlDocument.DocumentNode
             .Descendants()
             .Where(a => a.Attributes["id"]!=null && a.Attributes["id"].Value == "ct")
             .ToList();
    

    【讨论】: