从 C# 中的 HTML 代码获取特定单词的链接

Get links with specific words from a HTML code in C#

我正在尝试解析网站。我需要 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 代码中的所有链接。

我发现这个和那个对我有用。

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);
              }
        }

如果您有这样的 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>

您正在搜索以下单词:thewordother。您可以定义一个正则表达式,然后使用 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 关键字,但您必须为要搜索的每个词复制条件,例如:

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)')]")