Skip to main content
 首页 » 编程设计

c#之HTML敏捷包: get all elements by class

2024年02月13日96dflying

我有一个 HTML,我需要按类获取一些节点。所以我不能这样做,因为

  1. 我不知道 XML 路径
  2. 需要的元素没有ID,只有类
  3. HtmlAgilityPack 不允许获取所有元素(如 XDocument 允许),但 doc.Elements() 仅在我有 id 时才有效,但我没有.所以我也不知道 XML 路径,所以我不能使用 SelectNodes 方法
  4. 我不能使用正则表达式

我的代码是

public static class HapHelper 
{ 
    private static HtmlNode GetByAttribute(this IEnumerable<HtmlNode> htmlNodes, string attribute, string value) 
    { 
        return htmlNodes.First(d => d.HasAttribute(attribute) && d.Attributes[attribute].ToString() == value); 
    } 
 
    public static HtmlNode GetElemenyByAttribute(this HtmlNode parentNode, string attribute, string value) 
    { 
        return GetByAttribute(parentNode.Descendants(), attribute, value); 
    } 
 
    public static bool HasAttribute(this HtmlNode d, string attribute) 
    { 
        return d.Attributes.Contains(attribute); 
    } 
 
    public static HtmlNode GetElementByClass(this HtmlNode parentNode, string value) 
    { 
        return parentNode.GetElemenyByAttribute("class", value); 
    } 
} 

但它不起作用,因为 Descendants() 仅返回最近的节点。

我能做什么?

请您参考如下方法:

学习 XPath! :-) 这真的很简单,而且会很好地为您服务。在这种情况下,你想要的是:

SelectNodes("//*[@class='" + classValue + "']") ?? Enumerable.Empty<HtmlNode>();