HtmlAgilityPack/xpath

 【转载】HTML解析利器HtmlAgilityPack

在网上发现了一个.NET下的HTML解析类库HtmlAgilityPack。HtmlAgilityPack是一个支持用XPath来解析HTML的类库,在花了一点时间学习了解HtmlAgilityPack的API和XPath之后,周公就做了一个简单的工具完成了这个功能,目前在CSDN上周公博文的收集地址为:http://blog.csdn.net/zhoufoxcn/archive/2011/06/23/6564578.aspx,在51CTO上周公博文的收集地址为http://zhoufoxcn.blog.51cto.com/792419/595327。HtmlAgilityPack是一个开源的.NET类库,它的主页是http://htmlagilitypack.codeplex.com/,在这里可以下载到最新版的类库及API手册,此外还可以下载到一个用于调试的辅助工具。

XPath简明介绍
XPath 使用路径表达式来选取 XML 文档中的节点或节点集。节点是通过沿着路径 (path) 或者步 (steps) 来选取的。
下面列出了最有用的路径表达式:
nodename:选取此节点的所有子节点。
/:从根节点选取。
//:从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
.:选取当前节点。
..:选取当前节点的父节点。
例如有下面一段XML:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Articles>
  3. <Article>
  4. <Title>在ASP.NET中使用Highcharts js图表</title>
  5. <Url>http://zhoufoxcn.blog.51cto.com/792419/537324</Url>
  6. <CreateAt type="en">2011-04-07</price>
  7. </Article>
  8. <Article>
  9. <Title lang="eng">Log4Net使用详解(续)</title>
  10. <Url>http://blog.csdn.net/zhoufoxcn/archive/2010/11/23/6029021.aspx</Url>
  11. <CreateAt type="zh-cn">2010年11月23日</price>
  12. </Article>
  13. <Article>
  14. <Title>J2ME开发的一般步骤</title>
  15. <Url>http://blog.csdn.net/zhoufoxcn/archive/2011/06/12/6540223.aspx</Url>
  16. <CreateAt type="zh-cn">2011年06月12日</price>
  17. </Article>
  18. <Article>
  19. <Title lang="eng">PowerDesign高级应用</title>
  20. <Url>http://zhoufoxcn.blog.51cto.com/792419/166415</Url>
  21. <CreateAt type="zh-cn">2007-09-08</price>
  22. </Article>
  23. </Articles>


针对上面的XML文件,我们列出了带有谓语的一些路径表达式,以及表达式的结果:
/Articles/Article[1]:选取属于Articles子元素的第一个Article元素。
/Articles/Article[last()]:选取属于Articles子元素的最后一个Article元素。
/Articles/Article[last()-1]:选取属于Articles子元素的倒数第二个Article元素。
/Articles/Article[position()<3]:选取最前面的两个属于 bookstore 元素的子元素的Article元素。
//title[@lang]:选取所有拥有名为lang的属性的title元素。
//CreateAt[@type='zh-cn']:选取所有CreateAt元素,且这些元素拥有值为zh-cn的type属性。
/Articles/Article[Order>2]:选取Articles元素的所有Article元素,且其中的Order元素的值须大于2。
/Articles/Article[Order<3]/Title:选取Articles元素中的Article元素的所有Title元素,且其中的Order元素的值须小于3。

HtmlAgilityPack API简明介绍
在HtmlAgilityPack中常用到的类有HtmlDocument、HtmlNodeCollection、
HtmlNode和HtmlWeb等。
其流程一般是先获取HTML,这个可以通过HtmlDocument的Load()或LoadHtml()来加载静态内容,或者也可以HtmlWeb的Get()或Load()方法来加载网络上的URL对应的HTML。
得到了HtmlDocument的实例之后,就可以用HtmlDocument的DocumentNode属性,这是整个HTML文档的根节点,它本身也是一个HtmlNode,然后就可以利用HtmlNode的SelectNodes()方法返回多个HtmlNode的集合对象HtmlNodeCollection,也可以利用HtmlNode的SelectSingleNode()方法返回单个HtmlNode。

HtmlAgilityPack实战
下面是一个解析CSDN博客的代码实例:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using HtmlAgilityPack;
  5. using System.Text.RegularExpressions;
  6. namespace CrawlPageApplication
  7. {
  8. /**
  9. * 作者:周公
  10. * 日期:2011-06-23
  11. * Blog: http://blog.csdn.net/zhoufoxcn or http://zhoufoxcn.blog.51cto.com
  12. * Weibo: http://weibo.com/zhoufoxcn
  13. */
  14. public class CSDN_Parser
  15. {
  16. private const string CategoryListXPath = "//html[1]/body[1]/div[1]/div[1]/div[2]/div[1]/div[1]/dl[1]/dd[3]/div[1]/ul[1]/li";
  17. private const string CategoryNameXPath = "//li[1]/a[2]";
  18. /// <summary>
  19. /// 分析博客首页
  20. /// </summary>
  21. /// <param name="url"></param>
  22. /// <returns></returns>
  23. public static List<Category> ParseIndexPage(string url)
  24. {
  25. Uri uriCategory=null;
  26. List<Category> list = new List<Category>(40);
  27. HtmlDocument document = new HtmlDocument();
  28. //注意,这里省略掉了使用本人其它类库中加载URL的类,而是直接加载本地的HTML文件
  29. //string html = HttpWebUtility.ReadFromUrl(url, Encoding.UTF8);
  30. //document.LoadHtml(html);
  31. document.Load("CSDN_index.html", Encoding.UTF8);
  32. HtmlNode rootNode = document.DocumentNode;
  33. HtmlNodeCollection categoryNodeList = rootNode.SelectNodes(CategoryListXPath);
  34. HtmlNode temp = null;
  35. Category category = null;
  36. foreach (HtmlNode categoryNode in categoryNodeList)
  37. {
  38. temp = HtmlNode.CreateNode(categoryNode.OuterHtml);
  39. category = new Category();
  40. category.Subject = temp.SelectSingleNode(CategoryNameXPath).InnerText;
  41. Uri.TryCreate(UriBase, temp.SelectSingleNode(CategoryNameXPath).Attributes["href"].Value, out uriCategory);
  42. category.IndexUrl = uriCategory.ToString();
  43. category.PageUrlFormat=category.IndexUrl+"?PageNumber={0}";
  44. list.Add(category);
  45. Category.CategoryDetails.Add(category.IndexUrl, category);
  46. }
  47. return list;
  48. }
  49. }
  50. }


当然实现类似的解析51CTO的博客文章数据的代码如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using HtmlAgilityPack;
  5. using System.Text.RegularExpressions;
  6. namespace CrawlPageApplication
  7. {
  8. /**
  9. * 作者:周公
  10. * 日期:2011-06-23
  11. * Blog: http://blog.csdn.net/zhoufoxcn or http://zhoufoxcn.blog.51cto.com
  12. * Weibo: http://weibo.com/zhoufoxcn
  13. */
  14. public class CTO_Parser
  15. {
  16. private static Encoding PageEncoding = Encoding.GetEncoding("gb2312");
  17. private static readonly Uri UriBase = new Uri("http://zhoufoxcn.blog.51cto.com");
  18. private static string CategoryListXPath = "/html[1]/body[1]/div[5]/div[1]/div[1]/div[2]/ul[1]/li";
  19. private static string CategoryNameXPath = "/li[1]/a[1]";
  20. /// <summary>
  21. /// 分析博客首页
  22. /// </summary>
  23. /// <param name="url"></param>
  24. /// <returns></returns>
  25. public static List<Category> ParseIndexPage(string url)
  26. {
  27. Uri uriCategory = null;
  28. List<Category> list = new List<Category>(40);
  29. HtmlDocument document = new HtmlDocument();
  30. //string html = HttpWebUtility.ReadFromUrl(url, PageEncoding);
  31. //document.LoadHtml(html);
  32. document.Load("51cto_index.html", PageEncoding);
  33. HtmlNode rootNode = document.DocumentNode;
  34. HtmlNodeCollection categoryNodeList = rootNode.SelectNodes(CategoryListXPath);
  35. HtmlNode temp = null;
  36. Category category = null;
  37. foreach (HtmlNode categoryNode in categoryNodeList)
  38. {
  39. temp = HtmlNode.CreateNode(categoryNode.OuterHtml);
  40. if (temp.SelectSingleNode(CategoryNameXPath).InnerText != "全部文章")
  41. {
  42. category = new Category();
  43. category.Subject = temp.SelectSingleNode(CategoryNameXPath).InnerText;
  44. Uri.TryCreate(UriBase, temp.SelectSingleNode(CategoryNameXPath).Attributes["href"].Value, out uriCategory);
  45. category.IndexUrl = uriCategory.ToString();
  46. category.PageUrlFormat = category.IndexUrl + "/page/{0}";
  47. list.Add(category);
  48. Category.CategoryDetails.Add(category.IndexUrl, category);
  49. }
  50. }
  51. return list;
  52. }
  53. }
  54. }


在上面的代码中出现了一个Category类,该类的定义如下:
为了鼓励大家动手尝试以及在本项目中使用了周公的私家类库,所以不提供全部源代码下载,这里提供周公操作的最终软件界面:



总结:HtmlAgilityPack确实是一个功能强大、体积小的开源HTML解析类库,在本篇仅仅是介绍了其中几个类的用法,但光这些就足以供周公快速实现了许久没有实现的功能,如果让周公用正则表达式来实现类似的功能,时间肯定要比用这个长得多。
说明:周公最近也在琢磨一些关于微博的应用,如果有相同爱好者或者在使用微博的读者,请围观周公的微博,网址是:http://weibo.com/zhoufoxcn

2011-06-24
周公

原文地址:https://www.cnblogs.com/wangrsh2010/p/2184935.html