Cloud App -- Baidu App Engine爬虫应用开发

今天试用了一下百度云平台(http://yun.baidu.com/)的云环境Baidu App Engine(以下简称BAE),整体感觉还不错(毕竟是互联网巨头的产品啊)。整体使用类似Google的GAE和Sina的SAE,但是也做了依托搜索平台和海量数据过滤检索的特性。 本人使用其中的Mysql-分布式数据库服务,FetchUrl-Url抓取服务,Taskqueue-分布式队列服务。因为考虑分析url,fetch操作,故选择PHP作为BAE的开发语言。为了试手,简单的写了一个递归爬取Url的蜘蛛程序(BaeSpider),功能就是通过种子Url,通过,搜索链接,归并入数据库: 1、同步抓取 : spider.php从数据库抓取一个种子Url -> 通过FetchUrl抓取content(递归抓取) -> 通过regex分析出所有链接 -> 对每个分析出的url在数据库中进行归并索引 -> 将hit次数、httpcode等信息写回 2、异步抓取 : 从数据库抓取一个种子Url -> 种入Taskqueue队列 -> Taskqueue任务并发(此处并发不宜太高,因数据库链接有限)回调spider.php -> 通过FetchUrl抓取content -> 通过regex分析出所有链接 -> 对每个分析出的url在数据库中进行归并索引 -> 将hit次数、httpcode等信息写回。
  1. /**  
  2.  *  if we set ?url='http://www.sina.com.cn' like this , use it dierctly !  
  3.  *  otherwise we fetch a record from mysql  
  4.  */  
  5.  if (isset($arr['url']))   
  6.          $url = $arr['url'];   
  7.  else  
  8.          $url = $this->mysql_spld_random();   
  9.   
  10.  while($this->fetch_loop_max && $this->fetch_loop_max_retry) {   
  11.          $content = $this->fetch_url($url);   
  12.          if ($content) {   
  13.              // analyz all url from content   
  14.              preg_match_all("/http:\/\/([\w-]+\.)*(com|net|org|gov|cc|biz|info|cn)(\.(cn|hk))*/",$content,$regex_urls);   
  15.              foreach($regex_urls[0] as $value)   
  16.                  if (!in_array($value,$this->urls) && substr_count($value,'.')>=2)   
  17.                      array_push($this->urls,$value);   
  18.              $this->fetch_loop_max--;   
  19.          } else {   
  20.              $this->fetch_loop_max_retry--;   
  21.              $url = $this->mysql_spld_random();   
  22.          }   
  23.          // if we have crawled some urls , use them .   
  24.          $url = count($this->urls) ? $this->urls[array_rand($this->urls)] : $this->mysql_spld_random();   
  25.  }   
  26.  if (count($this->urls))   
  27.      foreach ($this->urls as $value)   
  28.          $this->mysql_spld_link_incr($value);   
  29.   
  30.  mysql_close($con);   
  31.   
  32.  if ($show) {   
  33.      echo count($this->urls)." urls crawled : <br />\n";   
  34.      echo $this->output;   
  35.  }  
通过并发抓取的大量url及各个url信息,可以记录它们的domain、http_cdoe、被链次数、pagerank(从alexa查询)等,再可以进行排名,或者得到一些热链和死链。 总结: 开发BaeSpider目的是为了简单应用一下BAE,并初步简单实现蜘蛛的雏形,还有很多需要完善之处。以后会通过其他服务(如类似GAE的Cron和Rank服务,猜想可能会开发吧)提供更多功能。现只提供了简单的url抓取功能,以后会考虑加入其他任务使得蜘蛛能够从content中获取更多的内容进行分析和展现。

posted on 2013-01-25 00:50  cnjack  阅读(286)  评论(0)    收藏  举报

导航