【问题标题】:How to parse an html node containing multiple tags?如何解析包含多个标签的html节点?
【发布时间】:2022-01-09 03:59:29
【问题描述】:

我能够到达我想要提取的节点,但不知道如何在节点中分隔不同的标签。

附言我对正则表达式没意见;只是好奇是否存在使用 Html Agility Pack 的更简单方法。

代码:

...
...
HtmlNodeCollection nodes = webContent.DocumentNode.SelectNodes("//*[@id='node-name']/ul/li");

foreach (HtmlNode node in nodes) {
    String link = ???; // extract the http link here (href)
    String text = ???; // extract the inner text here
    String nums = ???; // extract the content of <small> tag here
    ...
}

html 示例:

...
...
<ul class="some-class-name">
  <li>
    <a href="http://link-1.com">text for link 1<small>1</small></a>
  </li>
  <li>
    <a href="http://link-2.org">text for link 2<small>2</small></a>
  </li>
  <li>
    <a href="http://link-3.net">text for link 3<small>3</small></a>
  </li>
</ul>
...
...

【问题讨论】:

  • 你使用HtmlAgilityPack(它现在有点……死了)而不是像 AngleSharp 这样更现代的库有什么原因吗?
  • 哇,我上次使用AngleSharp(现在是几年前)它正在使用HtmlAgilityPack。这似乎不再是这种情况了。向AngleSharp 小组致敬,感谢@Dai 揭露这一点。
  • @Dai:你确定这些天是这样吗?几年前确实如此,当我们切换到 AngleSharp 时......但它已经过改造并且看起来很活跃:12

标签: c# html html-agility-pack


【解决方案1】:

您可以使用原生 API 中的元素或后代。
请记住,您可以使用诸如 this 之类的扩展来启用 css 选择器查询,据我了解,这是首选(也是最简单)的方式。

遵循代码sn-p:

    //https://stackoverflow.com/q/70203208/1219280
    var doc = new HtmlDocument();
    doc.LoadHtml(@"
        <ul class='some -class-name'>
          <li>
            <a href = 'http://link-1.com' > text for link 1<small>1</small></a>
          </li>
          <li>
            <a href = 'http://link-2.org' > text for link 2<small>2</small></a>
          </li>
          <li>
            <a href = 'http://link-3.net' > text for link 3<small>3</small></a>
          </li>
        </ul>
    ");

    Console.WriteLine("-------------------- Using Element(s) -------------------------");

    //using Element(s), queries children in the next level only
    var ul = doc.DocumentNode.Element("ul");
    var lis = ul.Elements("li");
    foreach(var li in lis)
    {
        var a = li.Element("a");
        var href = a?.GetAttributeValue("href");
        var smallText = a.Element("small")?.InnerText;

        Console.WriteLine($"a href: [{href}] small: [{smallText}]");
    }

    Console.WriteLine("-------------------- Using Descendants -------------------------");

    //using Descendants
    var anchors = doc.DocumentNode.Descendants("a");
    foreach(var a in anchors)
    {
        var href = a?.GetAttributeValue("href");
        var smallText = a.Element("small")?.InnerText;

        Console.WriteLine($"a href: [{href}] small: [{smallText}]");
    }

输出:

【讨论】:

    猜你喜欢
    • 2012-01-13
    • 2012-07-07
    • 2012-10-30
    • 2019-12-09
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 2016-02-26
    相关资源
    最近更新 更多