【问题标题】:Looping a node collection gives me unique nodes but selecting nodes inside from these give me the results of the first loop item循环节点集合给了我唯一的节点,但是从这些节点中选择节点给了我第一个循环项的结果
【发布时间】:2021-11-08 07:44:43
【问题描述】:

上下文:使用 HTMLAgilityPack 库,我循环一个 HtmlNodeCollection,打印节点的 HTML 为我提供了我需要的数据,但是当我在 html 中选择节点时,所有这些都给了我第一个项目的结果中的选定节点。

将节点 html 写为 node.InnerHtml 为我提供了它们的唯一 html,所有这些都是正确的,但是当我执行 SelectSingleNode 时,它​​们都给了我相同的数据。

由于项目原因,我不能透露网站。我能说的是,有 17 个节点,它们都是一个具有 k-user-item 类的 div。所有项目都是独一无二的,这意味着它们都是不同的。

感谢您的帮助!

代码:

var nodes = w.DocumentNode.SelectNodes("//div[contains(@class, 'k-user-item')]");

List<Sales> saleList = new List<Sales>();

foreach (HtmlNode node in nodes)
{
    //This line prints correct html, selecting single nodes gives me always the same data of the first item from the loop.
    //Debug.WriteLine(node.InnerHtml);


    string payout = node.SelectSingleNode("//*[@class=\"k-item--buy-date\"]").InnerText;
    string size = node.SelectSingleNode("//*[@class=\"k-panel-title\"]").SelectNodes("//span")[1].InnerText;
    var trNodes = node.SelectNodes("//tr");

    string status = trNodes[1].SelectSingleNode("//b").InnerText;
    string orderId = trNodes[2].SelectNodes("//td")[1].SelectSingleNode("//span").InnerHtml;
    string sellDate = node.SelectSingleNode("//*[@class=\"k-panel-heading\"]").SelectNodes("//small")[1].InnerHtml;

}

【问题讨论】:

    标签: c# html selectsinglenode selectnodes


    【解决方案1】:

    通过在 XPath 中添加一个“.”解决了这个问题。开始吧。

    不将点添加到 XPath 意味着节点将在整个文档中搜索,而不仅仅是在确切的节点 html 中搜索。

    【讨论】:

      猜你喜欢
      • 2023-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 2012-08-10
      • 2014-09-06
      相关资源
      最近更新 更多