关于crawler4j 爬虫

最近有需要用到爬虫程序,翻看了一下互联网上关于爬虫的一些介绍及一些开源的网络爬虫:

http://www.open-open.com/68.htm

发现用nutch的人比较多,随即拿来使用。之后觉得nutch太过复杂,适合大规模海量数据的爬取,我目前还没有这种需求,留着以后再做研究!

逐个看了看其它几个小的开源爬虫,发现太老不更新就是文档太少。


crawler4j是一个短小精悍的爬虫,且非常容易使用,项目主页:https://code.google.com/p/crawler4j/。当然,code.google.com经常会被间歇性的墙掉,要有点耐心!

用Git把源码下下来导入eclipse,JDK必需是1.7,否则报new ArrayList<>()不支持错误。

爬虫业务逻辑在src/main/java下,可直接运行src/test/java下edu.uci.ics.crawler4j.examples.basic.BasicCrawlController

很简洁,总共就35个类,架构也很清晰:

edu.uci.ics.crawler4j.crawler 基本逻辑和配置

edu.uci.ics.crawler4j.fetcher 爬取

edu.uci.ics.crawler4j.frontier URL队列相关

edu.uci.ics.crawler4j.parser 对爬取结果进行解析

edu.uci.ics.crawler4j.robotstxt 检查robots.txt是否存在

edu.uci.ics.crawler4j.url URL相关,主要是WebURL

edu.uci.ics.crawler4j.util 是工具类



提前说一下crawler4j中文乱码问题,爬取暂时没有发现有乱码问题,解析时出现乱码。原因是tika在解析HTML时会已meta charset编码做为默认编码,当该编码与实际编码不一致时则会出现乱码,这里将meta charset改为正确的编码,在Page.load中修改如下:

[java]  view plain copy
  1.    /** 
  2.     * Loads the content of this page from a fetched 
  3.     * HttpEntity. 
  4.     */  
  5. public void load(HttpEntity entity) throws Exception {  
  6.   
  7.     contentType = null;  
  8.     Header type = entity.getContentType();  
  9.     if (type != null) {  
  10.         contentType = type.getValue();  
  11.     }  
  12.   
  13.     contentEncoding = null;  
  14.     Header encoding = entity.getContentEncoding();  
  15.     if (encoding != null) {  
  16.         contentEncoding = encoding.getValue();  
  17.     }  
  18.   
  19.     Charset charset = ContentType.getOrDefault(entity).getCharset();  
  20.     if (charset != null) {  
  21.         contentCharset = charset.displayName();   
  22.     }  
  23.   
  24.     contentData = EntityUtils.toByteArray(entity);  
  25.     //中文乱码  
  26.     //if(contentCharset != null) contentData = new String(contentData, contentCharset).getBytes();  
  27.     if(charset != null) {  
  28.         String data = new String(contentData,contentCharset);  
  29.         data = data.replaceFirst(""+contentCharset);  
  30.         contentData = data.getBytes(contentCharset);  
  31.     }  

你可能感兴趣的:(Java)