如果你有一個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