Why Html Agility Pack? (以下简称HAP)
.Net下解析HTML文件有很多种选择,包括微软自己也提供MSHTML用于manipulate HTML文件。但是,经过我一段时间的搜索,Html Agility Pack浮出水面:它是Stackoverflow网站上推荐最多的C# HTML解析器。HAP开源,易用,解析速度快。
How to use HAP?
1. 下载http://htmlagilitypack.codeplex.com/
2. 解压
3. 在Visual Studio Solution里,右击project -> add reference -> 选择解压文件夹里的HTMLAgilityPack.dll -> 确定
4. 代码头部加入 using HtmlAgilityPack;
Done!
Quick Start:
HtmlWeb webClient = new HtmlWeb();
HtmlDocument doc = webClient.Load("http://xxx");
HtmlNodeCollection hrefList = doc.DocumentNode.SelectNodes(".//a[@href]");
if (hrefList != null)
{
foreach (HtmlNode href in hrefList)
{
HtmlAttribute att = href.Attributes["href"];
doSomething(att.Value);
}
}
以上代码示例load进来一个网页,提取所有的link(就是<a href=...></a>),遍历时提取出link的内容(href.Attributes["href"].Value)然后doSomething().