如何使用 htmlagilitypack 从子节点获取所有值?

How can i get all value from child node using htmlagilitypack?

我如何从子节点获取值,如 href 值,并使用 html 敏捷包和父节点的 class 名称将它们添加到列表中?

我试过这段代码但失败了

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();
  1. 获取所有后代 div。这包括 children children 的 children
  2. 只保留 class pagination
  3. div
  4. Select 第一个 div 符合我们的标准
  5. 再次获取所有后代,但是这次as
  6. 得到as的值href
  7. 过滤掉带有空值的链接(比如提交的第一个链接HTML