C#解析html文档 HTML解析利器HtmlAgilityPack

C#解析html文档

 

当我们需要解析一个web页面的时候,如果非常简单,可以用字符串查找的方式,复杂一点可以用正则表达式,但是有时候正则很麻烦的,因为html代码本身就比较麻烦,像常用的img标签,这个东东到了浏览器上就没了闭合标签(一直还没搞懂为什么),想用XML解析,也是同样的原因根本解析不了,今天发现一个解析html控件,用了一下,非常好用。

 

这个控件叫做Html Agility Pack,主页在这儿:http://htmlagilitypack.codeplex.com/

这儿还有一篇blog介绍怎么使用的 (English):http://olussier.net/2010/03/30/easily-parse-html-documents-in-csharp/

我直接把例子贴这儿,一看就明白。因为是作为xml解析的,所以呢,少不了XPath,如果不懂这个东西的话,赶紧看看吧,现在xpath语法都扩展到css里面了,语法比较简单,先看看基础的就行了。

 

最基本的使用方法不是SelectSingleNode,而是GetElementById,这是与XmlDocument不同的地方。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// The HtmlWeb class is a utility class to get the HTML over HTTP
HtmlWeb htmlWeb = new HtmlWeb();
  
// Creates an HtmlDocument object from an URL
HtmlAgilityPack.HtmlDocument document = htmlWeb.Load("http://www.somewebsite.com");
  
// Targets a specific node
HtmlNode someNode = document.GetElementbyId("mynode");
  
// If there is no node with that Id, someNode will be null
if (someNode != null)
{
  // Extracts all links within that node
  IEnumerable<htmlnode> allLinks = someNode.Descendants("a");
  
  // Outputs the href for external links
  foreach (HtmlNode link in allLinks)
  {
    // Checks whether the link contains an HREF attribute
    if (link.Attributes.Contains("href"))
    {
      // Simple check: if the href begins with "http://", prints it out
      if (link.Attributes["href"].Value.StartsWith("http://"))
        Console.WriteLine(link.Attributes["href"].Value);
    }
  }
}</htmlnode>

使用xpath

1
2
3
4
5
6
// Extracts all links under a specific node that have an href that begins with "http://"
HtmlNodeCollection allLinks = document.DocumentNode.SelectNodes("//*[@id='mynode']//a[starts-with(@href,'http://')]");
  
// Outputs the href for external links
foreach (HtmlNode link in allLinks)
    Console.WriteLine(link.Attributes["href"].Value);

One more

1
2
3
4
xpath = "//table[@id='1' or @id='2' or @id='3']//a[@onmousedown]";
xpath = "//ul[@id='wg0']//li[position()<4]/h3/a";
xpath = "//div[@class='resitem' and position()<4]/a";
xpath = "//li[@class='result' and position()<4]/a";

 

一句话,非常好用!

 
 
分类: XML/XSL
 
 
 
HTML解析利器HtmlAgilityPack                 2011-06-24 01:56:40    
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://zhoufoxcn.blog.51cto.com/792419/595344            
  

 在以前的项目中周公曾有解析HTML的情况,当时是采用正则表达式一步步将无关的HTML注释及JS代码部分删除掉,然后再用正则表达式找出需要提取的部分,可以说使用正则表达式来做是一个比较繁琐的过程,特别是对于正则表达式不是很熟悉或者要处理的HTML很复杂的情况下。前一阵子周公还是通过这个办法将http://wz.csdn.net/zhoufoxcn上保存的网址导入到http://cang.baidu.com,本来还想将周公博客上的文章好好整理一下,但是考虑到使用正则真的是很繁琐也很麻烦,所以就一直没有动手。  直到前两天在网上发现了一个.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.    
  7.  namespace CrawlPageApplication  
  8.  {  
  9.      /**  
  10.       * 作者:周公  
  11.       * 日期:2011-06-23  
  12.       * Blog: http://blog.csdn.net/zhoufoxcn or http://zhoufoxcn.blog.51cto.com  
  13.       * Weibo: http://weibo.com/zhoufoxcn  
  14.       */ 
  15.      public class CSDN_Parser  
  16.      {  
  17.          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";  
  18.          private const string CategoryNameXPath = "//li[1]/a[2]";  
  19.    
  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.                
  30.              HtmlDocument document = new HtmlDocument();  
  31.     //注意,这里省略掉了使用本人其它类库中加载URL的类,而是直接加载本地的HTML文件  
  32.              //string html = HttpWebUtility.ReadFromUrl(url, Encoding.UTF8);  
  33.              //document.LoadHtml(html);  
  34.              document.Load("CSDN_index.html", Encoding.UTF8);  
  35.              HtmlNode rootNode = document.DocumentNode;  
  36.              HtmlNodeCollection categoryNodeList = rootNode.SelectNodes(CategoryListXPath);  
  37.              HtmlNode temp = null;  
  38.              Category category = null;  
  39.              foreach (HtmlNode categoryNode in categoryNodeList)  
  40.              {  
  41.                  temp = HtmlNode.CreateNode(categoryNode.OuterHtml);  
  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+"?PageNumber={0}";  
  47.                  list.Add(category);  
  48.                  Category.CategoryDetails.Add(category.IndexUrl, category);  
  49.              }  
  50.              return list;  
  51.          }  
  52.    
  53.      }  
  54.  } 

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

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

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

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

本文出自 “周公(周金桥)的专栏” 博客,请务必保留此出处http://zhoufoxcn.blog.51cto.com/792419/595344

 

 

posted @ 2017-02-28 09:15  sky20080101  阅读(182)  评论(0)    收藏  举报