如果你有一个HTML文件中像这样:
<div class="a">
<a href="http://www.website.com/"></a>
<a href="http://www.website.com/notfound"></a>
<a href="http://www.website.com/theword"></a>
<a href="http://www.website.com/sub/theword"></a>
<a href="http://www.website.com/theword.html"></a>
<a href="http://www.website.com/other"></a>
</div>
你正在寻找例如下面的话:theword
和other
。您可以定义一个正则表达式,然后使用LINQ来获取链接匹配你的正则表达式像这样的属性href
:
Regex regex = new Regex("(theworld|other)", RegexOptions.IgnoreCase);
HtmlNode node = htmlDoc.DocumentNode.SelectSingleNode("//div[@class='a']");
List<HtmlNode> nodeList = node.SelectNodes(".//a").Where(a => regex.IsMatch(a.Attributes["href"].Value)).ToList<HtmlNode>();
List<string> urls = new List<string>();
foreach (HtmlNode n in nodeList)
{
urls.Add(n.Attributes["href"].Value);
}
注意,有一个contains
关键字使用XPath,但你必须复制的条件每个字你正在寻找这样的:
node.SelectNodes(".//a[contains(@href,'theword') or contains(@href,'other')]")
还有对XPATH一个matches
关键字,不幸的是它仅适用于XPath 2.0和HtmlAgilityPack使用XPath 1.0。使用XPATH 2.0,你可以这样做:
node.SelectNodes(".//a[matches(@href,'(theword|other)')]")
“HtmlNode links = ...;'的目的是什么?该声明是否应该删除? – AdrianHHH