HtmlAgilityPack - 后代的 SelectSingleNode

Jes*_*aya 1 html-agility-pack

我发现 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>
Run Code Online (Sandbox Code Playgroud)

不起作用的代码

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

我必须用以下代码替换上面的代码:

    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", "");
        }
    }
Run Code Online (Sandbox Code Playgroud)

我在 .Net Framework 4.6.2 上使用 HtmlAgilityPack 1.7.4

Dev*_*Guy 7

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

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

所以你的代码看起来像这样:

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