C# 如何使用HtmlAlityPack从子节点获取所有值?

C# 如何使用HtmlAlityPack从子节点获取所有值?,c#,html-agility-pack,C#,Html Agility Pack,如何从子节点(如href value)获取值,并使用具有父节点类名的html agility pack将其添加到列表中 我尝试过这个代码,但失败了 var pagedivs = htmlDocument.DocumentNode.SelectNodes("div").Where(e => e.GetAttributeValue("class", "").Equals("pagination")) .Where(k => k.Descendants().

如何从子节点(如href value)获取值,并使用具有父节点类名的html agility pack将其添加到列表中

我尝试过这个代码,但失败了

var pagedivs = htmlDocument.DocumentNode.SelectNodes("div").Where(e => e.GetAttributeValue("class", "").Equals("pagination"))
                .Where(k => k.Descendants().Any(t => t.Name == "li")).ToList();
网页中的HTML代码:

<div class="pagination">
        <ul class="pagination-list">
            <li class="hidden-phone current"><a title="1" href="" class="pagenav">1</a></li>
            <li class="hidden-phone"><a title="2" href="/collections/remarkable-products?page=2" class="pagenav">2</a></li>
            <li><a title="Next page" href="/collections/remarkable-products?page=2" class="pagenav"><i class="fa fa-chevron-right"></i></a></li>
        </ul>
        <input type="hidden" name="limitstart" value="0">
    </div>


要获取
href
值,您可以执行以下操作:

var links = document.DocumentNode
    .Descendants("div") // 1
    .Where(div => div.HasClass("pagination")) // 2
    .First() // 3
    .Descendants("a") // 4
    .Select(a => a.GetAttributeValue("href", "")) // 5
    .Where(link => !string.IsNullOrWhiteSpace(link)) // 6
    .ToList();
  • 获取所有子体
    div
    s。这包括儿童和儿童的儿童
  • 仅保留具有类
    分页的
    div
  • 选择符合我们标准的第一个
    div
  • 再次获取所有子体,但这次是
    a
    s
  • 获取
    a
    s
    href
    值的值
  • 过滤掉带有空值的链接(如提交的HTML中的第一个链接)