gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:33:40 25 4
gpt4 key购买 nike

我有一个 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>();

关于c# - HTML敏捷包: get all elements by class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22974491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com