【问题标题】:C# html agility pack get elements by class nameC# html 敏捷包按类名获取元素
【发布时间】:2022-03-07 21:05:07
【问题描述】:

我正在尝试获取他们的类包含某个单词的所有 div:

<div class="hello mike">content1</div>
<div class="hello jeff>content2</div>
<div class="john">content3</div>

我需要获取他们的类包含单词“hello”的所有 div。 像这样的:

resultContent.DocumentNode.SelectNodes("//div[@class='hello']"))

我如何使用敏捷包做到这一点?

【问题讨论】:

    标签: c# html html-agility-pack


    【解决方案1】:

    我明白了:

    resultContent.DocumentNode.SelectNodes("//div[contains(@class, 'hello')]")
    

    【讨论】:

      【解决方案2】:

      从 Html Agility Pack v1.6.5 版本开始,它包含.HasClass("class-name") 扩展方法。

      IEnumerable<HtmlNode> nodes =
          htmlDoc.DocumentNode.Descendants(0)
              .Where(n => n.HasClass("class-name"));
      

      【讨论】:

      • Above 比最流行的答案快 5 倍 - 尽管我使用 document.DocumentNode.Descendants().Where(x => x.HasClass(....
      【解决方案3】:

      我敢肯定,因为您的 div 中有多个类,所以这是行不通的。你可以试试这个:

      resultContent.DocumentNode.Descendants("div").Where(d => d.Attributes["class"].Value.Contains("hello"));
      

      【讨论】:

      • 与其他答案相比有一个缺点:如果有一个没有class 的 div,它会引发异常。改用这个:.Where(d =&gt; d.GetAttributeValue("class", "").Contains("hello"));
      【解决方案4】:

      由于您已指定该类必须包含某个单词,因此以下将确保该单词是:

      • 在字符串的开头,后跟一个空格
      • 或在字符串中间并被空格包围
      • 或在字符串的末尾并以空格开头
      • 或类属性中唯一的类名

      它通过比较由空格包围的类属性的值与由空格包围的指定单词 (hello) 来实现。这是为了避免像class="something-hello-something"这样的误报

      resultContent.DocumentNode.SelectNodes("//div[contains(concat(' ', @class, ' '), ' hello ')]");
      

      【讨论】:

        【解决方案5】:
        HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
        htmlDoc.Load(filePath);
         foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//div[@class='hello']")
         {
            //code
         }
        

        【讨论】:

        • 不起作用。 OP 尝试查找类 包含 一个单词作为子字符串的所有 div,例如 hello。您只选择类 hello 的 div
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-04
        • 2014-05-14
        • 1970-01-01
        • 2011-04-18
        • 2011-07-16
        • 2020-09-17
        • 2014-03-07
        相关资源
        最近更新 更多