HtmlAgilityPack:按类获取所有元素
本文关键字:元素 获取 HtmlAgilityPack | 更新日期: 2023-09-27 17:57:43
我有一个HTML,我需要按类获取一些节点。所以我不能这么做,因为
- 我不知道XML路径
- 所需项目没有ID,只有类
- HtmlAgilityPack不允许获取所有元素(就像
XDocument
允许的那样),但doc.Elements()
只有在我有id的情况下才能工作,但我没有。所以我也不知道XML路径,所以我不能使用SelectNodes
方法 - 我无法使用regexp
我的代码是
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>();