【发布时间】:2011-06-17 16:18:55
【问题描述】:
我有一个包含整个网页 HTML 的字符串变量。 该网页将包含指向其他网站的链接。我想创建一个所有hrefs的列表(webcrawler like )。 最好的方法是什么? 使用任何扩展功能会有帮助吗?使用正则表达式怎么样?
提前致谢
【问题讨论】:
我有一个包含整个网页 HTML 的字符串变量。 该网页将包含指向其他网站的链接。我想创建一个所有hrefs的列表(webcrawler like )。 最好的方法是什么? 使用任何扩展功能会有帮助吗?使用正则表达式怎么样?
提前致谢
【问题讨论】:
使用 DOM 解析器(例如 HTML Agility Pack)来解析您的文档并找到所有链接。
关于如何使用 HTML Agility Pack 有一个很好的问题here。下面是一个简单的示例来帮助您入门:
string html = "your HTML here";
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var links = doc.DocumentNodes.DescendantNodes()
.Where(n => n.Name == "a" && n.Attributes.Contains("href")
.Select(n => n.Attributes["href"].Value);
【讨论】:
【讨论】:
我会选择正则表达式。
Regex exp = new Regex(
@"{href=}*{>}",
RegexOptions.IgnoreCase);
string InputText; //supply with HTTP
MatchCollection MatchList = exp.Matches(InputText);
【讨论】:
试试这个正则表达式(应该可以):
var matches = Regex.Matches (html, @"href=""(.+?)""");
您可以浏览匹配项并提取捕获的 URL。
【讨论】:
您是否考虑过使用 HTMLAGILITYPACK? http://htmlagilitypack.codeplex.com/
有了这个,您可以简单地使用 XPATH 来获取页面上的所有链接并将它们放入一个列表中。
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;
}
取自这里的另一个帖子 - Get all links on html page?
【讨论】: