【问题标题】:Get all links on html page?获取html页面上的所有链接?
【发布时间】:2011-01-15 22:41:44
【问题描述】:

我正在做一个小爱好项目。我已经编写了获取 url、下载 header 并返回 mime 类型/内容类型的代码。

但是,在此之前的步骤是我坚持的步骤 - 我需要检索页面上基于标签内的所有 url 的内容,并用引号括起来,即

...
<link rel='shortcut icon' href="/static/favicon.ico" type="image/x-icon" />
...

会找到网站图标链接。

.net 库中是否有任何有用的东西,或者这是否必须是正则表达式的一个案例?

【问题讨论】:

  • 我有一种奇怪的感觉,那就是 Html 敏捷包是要走的路...

标签: c# asp.net


【解决方案1】:

我会考虑使用Html Agility Pack

这是一个直接来自他们的示例页面的示例,说明如何查找页面中的所有链接:

 HtmlWeb hw = new HtmlWeb();
 HtmlDocument doc = hw.Load(/* url */);
 foreach(HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
 {

 }

【讨论】:

  • 只是想补充一点,如果您尝试加载的网站有一些 gzip 压缩,它将在hw.Load 上抛出异常:"'gzip' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method。找到了解决方法here
  • 小心。这是获得 NullReferenceException 的机会。 Returns: An HtmlAgilityPack.HtmlNodeCollection containing a collection of nodes matching the HtmlAgilityPack.HtmlNode.XPath query, or null if no node matched the XPath expression
【解决方案2】:

BCL 中没有内置任何内容,但幸运的是,您可以使用 HTML Agility Pack 非常简单地完成此任务。

至于你的具体问题,请看Easily extracting links from a snippet of html with HtmlAgilityPack

private List<string> ExtractAllAHrefTags(HtmlDocument htmlSnippet)
{
    List<string> hrefTags = new List<string>();

    foreach (HtmlNode link in htmlSnippet.DocumentNode.SelectNodes("//a[@href]"))
    {
        HtmlAttribute att = link.Attributes["href"];
        hrefTags.Add(att.Value);
    }

    return hrefTags;
}

【讨论】:

  • 我不同意基于 LINQ 的方法更简单。声明式的?是的。功能性?绝对地。更简单?不,两种解决方案在简单性上是相同的。
  • XPath 应该使用更少的内存
  • 我建议使用 XPath 会减少内存密集度。
【解决方案3】:

您需要使用HTML Agility Pack

例如:

var doc = new HtmlWeb().Load(url);
var linkTags = doc.DocumentNode.Descendants("link");
var linkedPages = doc.DocumentNode.Descendants("a")
                                  .Select(a => a.GetAttributeValue("href", null))
                                  .Where(u => !String.IsNullOrEmpty(u));

【讨论】:

  • 感谢您使用全面且不言自明的 LINQ 查询!
【解决方案4】:

正则表达式怎么样?

<(a|link).*?href=(\"|')(.+?)(\"|').*?>

带有标志IgnoreCaseSingleLine

systemtextregularexpressions.com regex.matches上查看演示

【讨论】:

  • 这比求助于整个 3rd 方库更好。
猜你喜欢
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-19
  • 1970-01-01
  • 2016-12-14
  • 2023-04-02
相关资源
最近更新 更多