Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用html agility pack在类中获取链接_C#_Html Agility Pack - Fatal编程技术网

C# 使用html agility pack在类中获取链接

C# 使用html agility pack在类中获取链接,c#,html-agility-pack,C#,Html Agility Pack,类alt有很多tr。我想得到所有的链接(或者最后的第一个),但我不知道如何使用html敏捷包 我尝试了a的变体,但我只得到了所有链接,或者没有。它似乎不是只得到节点中的一个,因为我正在写n.SelectNodes,所以它没有意义 html.LoadHtml(page); var nS = html.DocumentNode.SelectNodes("//tr[@class='alt']"); foreach (var n in nS) { var aS = n.SelectNodes("a"

类alt有很多tr。我想得到所有的链接(或者最后的第一个),但我不知道如何使用html敏捷包

我尝试了a的变体,但我只得到了所有链接,或者没有。它似乎不是只得到节点中的一个,因为我正在写n.SelectNodes,所以它没有意义

html.LoadHtml(page);
var nS = html.DocumentNode.SelectNodes("//tr[@class='alt']");
foreach (var n in nS)
{
  var aS = n.SelectNodes("a");
  ...
}
您可以使用LINQ:

var links = html.DocumentNode
           .Descendants("tr")
           .Where(tr => tr.GetAttributeValue("class", "").Contains("alt"))
           .SelectMany(tr => tr.Descendants("a"))
           .ToArray();
请注意,这也将匹配
;您可能希望用正则表达式替换
Contains
调用

您还可以使用:


请注意,这两种方法还将返回非链接的锚点。

为什么不在单个查询中选择所有链接:

html.LoadHtml(page);
var nS = html.DocumentNode.SelectNodes("//tr[@class='alt']//a");
foreach(HtmlNode linkNode in nS)
{
//do something
}
它对html有效:

<table>
<tr class = "alt">
<td><'a href="link.html">Some Link</a></td>
</tr>
</table>


您可以显示您试图解析的html的一个片段吗?我不完全清楚你想说什么do@jaltiere:他想要CSS选择器
tr.alt a
<table>
<tr class = "alt">
<td><'a href="link.html">Some Link</a></td>
</tr>
</table>