XPath 有一个contains
方法,所以很简单:
var urls = new List<Uri>();
var url = new Uri("http://stackoverflow.com/questions/12131954/");
using (var client = new WebClient())
{
var doc = new HtmlDocument();
doc.Load(client.OpenRead(url));
var links = doc.DocumentNode.SelectNodes("//a[contains(@href,'stackoverflow.com')]");
foreach (var link in links)
{
var uri = new Uri(url, link.Attributes["href"].Value); //fixes relative Urls
if (uri.Scheme.StartsWith("http"))
{
urls.Add(uri);
}
}
Console.WriteLine(urls);
}
或者您可以使用 Linq 获取链接
var links = doc.DocumentNode.Descendants("a")
.Where(a => a.Attributes["href"] != null
&& a.Attributes["href"].Value.ToLower().Contains("stackoverflow.com"));
此外,您似乎是从子节点匹配的,如果您想使用相同的 XPath,则必须在字符串的开头添加一个点.//a[]