C#文章采集浅析

来源:互联网 发布:神作 知乎 编辑:程序博客网 时间:2024/04/30 09:40
以前写了篇“百度视频采集"的思路简介,看到唯一一个人留言希望我总结一下新闻采集。今天就拿博客园的热门文章采集做个例子。说明前我得声明一点,经过在博客园混了几个月后,发现博客园首页发布的文章一般都是高手,很有参考价值。可我是一个新手,我请大家此文章的任何质疑直接留言,因为您发现问题不说出来,可能我永远会认为自己写的是正确的。

      下面进入正题。首先需要注意的是采集网页上数据的唯一方式是必须获取需要采集页面的源代码,这点想必大家很清楚。因为我们不知道对方网站的数据库服务器连接方式,我们只能在页面的源代码中找寻我们想要的东西。这无疑就是对大量字符串进行处理,那么我们如何处理这些含有大量html标记与内容的代码呢?可能解决问题的方式有很多种,但我认为用正则表达式来解决这个问题会很好。

      通过上面的话,我谈到了两个知识点,我们来总结一下流程。

      1.获取需要采集页面的源代码。
      2.利用正则表达式处理这些代码中我们想要的内容。

      下面做一些准备工作,写一个实体类存储文章的信息。例如:标题、作者、发布时间、浏览次数,等。
文章信息实体类
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;

  4. namespace Plug.Article.Entity
  5. {
  6.     /**//// <summary>
  7.     /// 采集文章信息,部分属性可留空。标题与地址如为空则默认赋值时引发异常
  8.     /// </summary>
  9.     [Serializable]
  10.     public class Article
  11.     {
  12.         private string category;

  13.         /**//// <summary>
  14.         /// 文章类别
  15.         /// </summary>
  16.         public string Category
  17.         {
  18.             get { return category; }
  19.             set { category = value; }
  20.         }
  21.         private string url;
  22.         /**//// <summary>
  23.         /// 文章连接地址
  24.         /// </summary>
  25.         public string Url
  26.         {
  27.             get
  28.             {
  29.                 return url;
  30.             }
  31.             set
  32.             {
  33.                 if (value == "" || value.Length <= 0)
  34.                 {
  35.                     throw new ApplicationException("文章的连接地址不能为空!");
  36.                 }
  37.                 url = value;
  38.             }
  39.         }
  40.         private string title;
  41.         /**//// <summary>
  42.         /// 文章标题
  43.         /// </summary>
  44.         public string Title
  45.         {
  46.             get
  47.             {
  48.                 return title;
  49.             }
  50.             set
  51.             {
  52.                 if (value == "" || value.Length <= 0)
  53.                 {
  54.                     throw new ApplicationException("文章的标题不能为空!");
  55.                 }
  56.                 title = value;
  57.             }
  58.         }
  59.         private int views;
  60.         /**//// <summary>
  61.         /// 文章浏览次数
  62.         /// </summary>
  63.         public int Views
  64.         {
  65.             get
  66.             {
  67.                 return views;
  68.             }
  69.             set
  70.             {
  71.                 views = value;
  72.             }
  73.         }
  74.         private int replys;
  75.         /**//// <summary>
  76.         /// 文章评论次数
  77.         /// </summary>
  78.         public int Replys
  79.         {
  80.             get
  81.             {
  82.                 return replys;
  83.             }
  84.             set
  85.             {
  86.                 replys = value;
  87.             }
  88.         }
  89.         private string datatime;
  90.         /**//// <summary>
  91.         /// 文章发布日期
  92.         /// </summary>
  93.         public string Datatime
  94.         {
  95.             get
  96.             {
  97.                 return datatime;
  98.             }
  99.             set
  100.             {
  101.                 datatime = value;
  102.             }
  103.         }
  104.         private string author;
  105.         /**//// <summary>
  106.         /// 文章作者
  107.         /// </summary>
  108.         public string Author
  109.         {
  110.             get
  111.             {
  112.                 return author;
  113.             }
  114.             set
  115.             {
  116.                 author = value;
  117.             }
  118.         }
  119.         private string site;
  120.         /**//// <summary>
  121.         /// 文章作者网站、文章采集网站
  122.         /// </summary>
  123.         public string Site
  124.         {
  125.             get
  126.             {
  127.                 return site;
  128.             }
  129.             set
  130.             {
  131.                 site = value;
  132.             }
  133.         }
  134.     }
  135. }
复制代码
获取采集网页源代码的方式,也很简单,我单独做成了一个类。
获取网页源代码
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net;

  5. namespace Plug.Article
  6. {
  7.     /**//// <summary>
  8.     /// 网页操作类
  9.     /// </summary>
  10.     public class HTML
  11.     {
  12.         /**//// <summary>
  13.         /// 获取网页源代码
  14.         /// </summary>
  15.         /// <param name="url">URL路径</param>
  16.         /// <returns></returns>
  17.         public string GetHTML(string url)
  18.         {
  19.             WebClient web = new WebClient();
  20.             byte[] buffer = web.DownloadData(url);
  21.             return Encoding.Default.GetString(buffer);
  22.         }
  23.     }
  24. }
复制代码
拿到源代码,该进入关键步骤了,写正则表达式采集数据。在采集之前我们需要了解网页源代码的特征,如果都不知道我们想要什么,恐怕无法写出正则表达式。我们要采集的页面是 http://www.cnblogs.com/TopPosts.aspx 这个页面,博客园文章阅读排行榜。今日阅读排行、 昨日阅读排行 等信息。但我们要得到的只是如下信息:

· 我在外资公司的2个月 (阅读:1909) (评论:21) (2008-6-25 13:44)yesry· 为什么尽量避免使用触发器? (阅读:1490) (评论:15) (2008-6-25 03:35)凉面· Discuz!NT 系统架构分析 (阅读:1391) (评论:18) (2008-6-25 12:35)韩龙· 硬盘那点事儿 (阅读:1342) (评论:15) (2008-6-25 11:16)李战
只需要得到标题、阅读次数、评论、时间、作者即可。那么我们就来分析一下关键信息的源代码特征。
  1.         <tr>
  2.             <td style="width:80%">
  3.                 · <a id="ctl00_cphMain_TopPostsPaged1_PostsRepeater_ctl01_lnkTitle" href="http://www.cnblogs.com/yesry/archive/2008/06/25/1229587.html" target="_blank">我在外资公司的2个月</a> <span class="title">(阅读:1909) (评论:21) (2008-6-25 13:44)</span>

  4.             </td>
  5.             <td height="20">
  6.                 <a id="ctl00_cphMain_TopPostsPaged1_PostsRepeater_ctl01_lnkAuthor" href="http://yesry.cnblogs.com/">yesry</a>
  7.             </td>
  8.         </tr>
复制代码
这就是我们需要采集信息的源代码。在开始写正则表达式之前我需要说明一点,我们都知道,这些内容也是动态产生的。所以它们的格式肯定是固定的。这样我们就可以利用一个正则表达式正确的采集到该页面所有信息。我觉得没必要在这片文章中详细解释正则表达式的含义,因为这需要多练习。
  1. Regex regexarticles = new Regex(".+· <a\\s+id=\".+\" href=\"(?<url>.+)\"\\s+target=\"_blank\">(?<title>.+)</a> <span\\s+class=\".+\">\\(阅读:(?<views>\\d+)\\).*\\(评论:(?<reply>\\d+)\\).*\\((?<time>.+)\\)</span>\\s*</td>\\s*<td\\s+height=\"\\d+\">\\s+<a\\s+id=\".+\" href=\"(?<blog>.+)\">(?<author>.+)</a>");
复制代码
这些让您可能阅读起来很吃力,但我想学过正则表达式的人会嘲笑我,因为我的正则写的不够灵活。我要为没有接触过正则表达式的朋友简单介绍下,我也只是刚入门。正则表达式就是通过描述字符串的特征来进行匹配。这也是我们为什么需要分析页面源代码的原因。至于怎么去匹配,其实也不难,我提供一些文章给各位参考。
正则表达式学习笔记:http://hedong.3322.org/archives/000244.html
正则表达式30分钟入门:http://unibetter.com/deerchao/zhengzhe-biaodashi-jiaocheng-se.htm

我就是通过这两篇文章入门,并利用正则表达式写出了我喜欢的程序。至于更多的文章可以去网络寻找。

上面说到的是关键的正则表达式,下面还需要说一下怎么去取。

采集关键代码
  1.             //网页操作对象,我用来获取网页源码
  2.             HTML html = new HTML();

  3.             //对博客园每日排行数据进行采集
  4.             string htmlcode = html.GetHTML("http://www.cnblogs.com/TopPosts.aspx","utf-8");

  5.             //提取博客园排行文章信息的正则表达式
  6.             Regex regexarticles = new Regex(".+· <a\\s+id=\".+\" href=\"(?<url>.+)\"\\s+target=\"_blank\">(?<title>.+)</a> <span\\s+class=\".+\">\\(阅读:(?<views>\\d+)\\).*\\(评论:(?<reply>\\d+)\\).*\\((?<time>.+)\\)</span>\\s*</td>\\s*<td\\s+height=\"\\d+\">\\s+<a\\s+id=\".+\" href=\"(?<blog>.+)\">(?<author>.+)</a>");

  7.             //所有匹配表达式的内容
  8.             MatchCollection marticles = regexarticles.Matches(htmlcode);  

  9.             /**////遍历匹配内容
  10.             foreach (Match m in marticles)
  11.             {
  12.                 Entity.Article test = new Entity.Article();
  13.                 test.Category = "博客园热门文章";          //设置分类
  14.                 test.Title = m.Groups["title"].Value;      //设置标题
  15.                 test.Url = m.Groups["url"].Value;          //设置连接
  16.                 test.Views = int.Parse(m.Groups["views"].Value);    //设置浏览次数
  17.                 test.Replys = int.Parse(m.Groups["reply"].Value);  //设置评论次数
  18.                 test.Datatime = m.Groups["time"].Value;            //设置发布时间
  19.                 test.Author = m.Groups["author"].Value;            //设置作者
  20.                 test.Site = m.Groups["blog"].Value;                //设置文章出处
  21.                 list.Add(test);
  22.             }
  23.       MatchCollection marticles = regexarticles.Matches(htmlcode);
复制代码
通过此句代码获取多个匹配的内容。
  1. foreach (Match m in marticles)
复制代码
循环时需要用Match类取一条匹配内容,m.Groups["title"].Value  取出指定分组中的信息,这个分组是指(?<title>.+) ,“?<title>”这就是给匹配内容分组为title的代码。代码就是这样了,没有什么技术含量,来总结一下做采集的一个流程吧。
      1.取指定页面的源代码
      2.分析源代码中我们想要获得内容的特征
      3.通过特征写出正则表达式进行匹配
      4.遍历匹配内容装入集合

      流程就是这样,我把整个案例的代码打包供大家参考,如有什么问题请留言。

      采集出的数据可能与博客园显示顺序不太一致,因为是整个页面的文章,没有做分类处理。但数据绝对是一致的。

      源码下载:
cnblogsarticle.rar
原创粉丝点击