我正在尝试解析一个网站。我需要HTML文件中的一些链接,其中包含一些特定的单词。我知道如何找到“href”属性,但我不需要所有属性,无论如何要做到这一点?例如,我可以在HtmlAgilityPack中使用正则表达式吗?
HtmlNode links = document.DocumentNode.SelectSingleNode("//*[@id='navigation']/div/ul");
foreach (HtmlNode urls in document.DocumentNode.SelectNodes("//a[@]"))
{
this.dgvurl.Rows.Add(urls.Attributes["href"].Value);
}
我正在尝试这个以查找HTML代码中的所有链接。
如果您有这样的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);
}
请注意,XPATH contains
一个contains
关键字,但您必须复制您正在搜索的每个单词的条件:
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 = document.DocumentNode.SelectSingleNode("//*[@id='navigation']/div/ul");
foreach (HtmlNode urls in document.DocumentNode.SelectNodes("//a[@]"))
{
var temp = catagory.Attributes["href"].Value;
if (temp.Contains("some_word"))
{
dgv.Rows.Add(temp);
}
}