【问题标题】:HtmlAgilityPack - SelectSingleNode for descendantsHtmlAgilityPack - 后代的 SelectSingleNode
【发布时间】:2018-04-13 14:06:58
【问题描述】:

我发现 HtmlAgilityPack SelectSingleNode 总是从原始 DOM 的第一个节点开始。是否有等效的方法来设置其起始节点?

示例 html

<html>
  <body>
    <a href="https://home.com">Home</a>
    <div id="contentDiv">
    <tr class="blueRow">
        <td scope="row"><a href="https://iwantthis.com">target</a></td>
    </tr>
    </div>
  </body>
</html>

代码无效

//Expected:iwantthis.com  Actual:home.com, 
string url = contentDiv.SelectSingleNode("//tr[@class='blueRow']")
                       .SelectSingleNode("//a") //What should this be ?
                       .GetAttributeValue("href", "");

我必须用这个替换上面的代码:

    var tds = contentDiv.SelectSingleNode("//tr[@class='blueRow']").Descendants("td");
    string url = "";
    foreach (HtmlNode td in tds)
    {
        if (td.Descendants("a").Any())
        {
            url= td.ChildNodes.First().GetAttributeValue("href", "");
        }
    }

我在 .Net Framework 4.6.2 上使用 HtmlAgilityPack 1.7.4

【问题讨论】:

    标签: html-agility-pack


    【解决方案1】:

    您使用的 XPath 始终从文档的根目录开始。 SelectSingleNode("//a") 表示从文档的根目录开始,在文档的任意位置找到第一个a;这就是它抓取主页链接的原因。

    如果你想从当前节点开始,你应该使用.选择器。 SelectSingleNode(".//a") 意味着找到当前节点下方任意位置的第一个 a

    所以你的代码应该是这样的:

    string url = contentDiv.SelectSingleNode(".//tr[@class='blueRow']")
                       .SelectSingleNode(".//a")
                       .GetAttributeValue("href", "");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      相关资源
      最近更新 更多