我发现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框架4.6.2上使用.Net 1.7.4
发布于 2018-04-13 19:14:42
您使用的XPath总是从文档的根开始。SelectSingleNode("//a")意味着从文档的根目录开始,并在文档中的任何地方找到第一个a;这就是它获取主页链接的原因。
如果要从当前节点开始,则应使用.选择器。SelectSingleNode(".//a")意味着查找当前节点下任何位置的第一个a。
所以您的代码将如下所示:
string url = contentDiv.SelectSingleNode(".//tr[@class='blueRow']")
.SelectSingleNode(".//a")
.GetAttributeValue("href", "");https://stackoverflow.com/questions/49818917
复制相似问题