HtmlAgilityPack - 后代的 SelectSingleNode

HtmlAgilityPack - SelectSingleNode for descendants

我发现HtmlAgilityPackSelectSingleNode总是从原来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

您使用的 XPath 总是从文档的根开始。 SelectSingleNode("//a")表示从文档的根开始,找到文档中任意位置的第一个a;这就是为什么它占据了首页 link.

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

因此您的代码将如下所示:

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