Nutch教程——导入Nutch工程,执行完整爬取

在使用本教程之前,需要满足条件:

  • 1)有一台Linux或Linux虚拟机
  • 2)安装JDK(推荐1.7)
  • 3)安装Apache Ant

下载Nutch源码:

推荐使用Nutch 1.9,官方下载地址:http://mirrors.hust.edu.cn/apache/nutch/1.9/apache-nutch-1.9-src.zip

安装IDE:

推荐使用Intellij或者Netbeans,如果用eclipse也可以,不推荐。 Intellij官方下载地址:http://www.jetbrains.com/idea/download/

转换: Nutch源码是用ant进行构建的,需要转换成eclipse工程才可以导入IDE正确使用,Intellij和Netbeans都可以支持ecilpse工程。 解压下载的apache-nutch-1.9-src.zip,得到文件夹apache-nutch-1.9。

在执行转换之前,我们先修改一下ivy中的一个源,将它改为开源中国的镜像,否则转换的过程会非常缓慢。(ant源码中并没有附带依赖jar包,ivy负责从网上自动下载jar包)。 修改apache-nutch-1.9文件夹中的ivy/ivysettings.xml:

Nutch教程

找到:

  1. <property name="repo.maven.org"
  2. value="http://repo1.maven.org/maven2/"
  3. override="false"/>

Nutch教程

将value修改为http://maven.oschina.net/content/groups/public/ ,修改后:

  1. <property name="repo.maven.org"
  2. value="http://maven.oschina.net/content/groups/public/"
  3. override="false"/>

Nutch教程

保存并退出,保证当前目录为apache-nutch-1.9,执行命令:

  1. ant eclipse -verbose

然后耐心等待,这个过程ant会根据ivy从中心仓库下载各种依赖jar包,可能要十几分钟。

Nutch教程

-verbose参数加上之后可以看到ant过程的详细信息。

10分钟左右,转换成功:

Nutch教程

打开Intellij, File -> Import Project ->选择apache-nutch-1.9文件夹,确定后选择Import project from external model(Eclipse)

Nutch教程

一直点击next到结束。成功将项目导入Intellij:

Nutch教程

源码导入工程后,并不能执行完整的爬取。Nutch将爬取的流程切分成很多阶段,每个阶段分别封装在一个类的main函数中。在外面通过Linux Shell调用这些main函数,来完整爬取的流程。我们在后续教程中会对流程调度做一个详细的说明。

下面我们来运行Nutch中最简单的流程:Inject。我们知道爬虫在初始阶段,是需要人工给出一个或多个url,作为起始点(广度遍历树的树根)。Inject的作用,就是把用户写在文件里的种子(一行一个url,是TextInputFormat),插入到爬虫的URL管理文件(crawldb,是SequenceFile)中。 从src文件夹中找到org.apache.nutch.crawl.Injector类:

Nutch教程

在阅读Nutch源码的过程中,最重要的就是找到每个类的main函数:

Nutch教程

可以看到,main函数其实是利用ToolRunner,执行了run(String[] args)。这里ToolRunner.run会从第二个参数(new Injector())这个对象中,找到run(String[] args)这个方法执行。

从run方法中可以看出来,String[] args需要有2个参数,第一个参数表示爬虫的URL管理文件夹(输出),第二个参数表示种子文件夹(输入)。对hadoop中的map reduce程序来说,输入文件夹是必须存在的,输出文件夹应该不存在。我们创建一个文件夹 /tmp/urls,来存放种子文件(作为输入)。

Nutch教程

在seed.txt中加入一个种子URL

  1. http://www.cnbeta.com/

指定一个文件夹/tmp/crawldb来作为URL管理文件夹(输出) 有一种简单的方法来指定args,直接在main函数下加一行:

Nutch教程

  1. args=new String[]{"/tmp/crawldb","/tmp/urls"};

运行这个类,我们会发现报错了(下面只给了错误的一部分):

  1. Caused by: java.lang.RuntimeException: x point org.apache.nutch.net.URLNormalizer not found.
  2. at org.apache.nutch.net.URLNormalizers.<init>(URLNormalizers.java:123)
  3. at org.apache.nutch.crawl.Injector$InjectMapper.configure(Injector.java:84)
  4. ... 23 more

这是因为用这种方式执行,按照Nutch默认的配置,不能正确地加载插件。我们需要修改Nutch的配置文件,为插件文件夹指定一个绝对路径,修改conf/nutch-default.xml文件,找到:

  1. <property>
  2. <name>plugin.folders</name>
  3. <value>plugins</value>
  4. <description>Directories where nutch plugins are located. Each
  5. element may be a relative or absolute path. If absolute, it is used
  6. as is. If relative, it is searched for on the classpath.</description>
  7. </property>

将value修改为绝对路径 apache-nutch-1.9所在文件夹+”/src/plugin”,比如我的配置:

  1. <property>
  2. <name>plugin.folders</name>
  3. <value>/home/hu/apache/apache-nutch-1.9/src/plugin</value>
  4. <description>Directories where nutch plugins are located. Each
  5. element may be a relative or absolute path. If absolute, it is used
  6. as is. If relative, it is searched for on the classpath.</description>
  7. </property>

建议在修改nutch-default.xml时,将原来的配置注释,并复制一份新的修改,方便还原:

现在再运行Injector.java,看到结果:

Nutch教程

运行成功。

读取爬虫文件:

我们查看程序的输出 tree /tmp/crawldb ,如果没有tree命令,就直接用资源管理器之类的查看吧:

Nutch教程

查看里面的data文件:

  1. vim /tmp/crawldb/current/part-00000/data

Nutch教程

这是一个SequenceFile,Nutch中除了Inject的输入(种子)之外,其他文件 全部以SequenceFile的形式存储。SequenceFile的结构如下:

  1. key0 value0
  2. key1 value1
  3. key2 value2
  4. ......
  5. keyn valuen

以key value的形式,将对象序列(key value序列)存储到文件中。我们从SequenceFile头部可以看出来key value的类型。

上面的SequenceFile中,可以看出来,key的类型是org.apache.hadoop.io.Text,value的类型是org.apache.nutch.crawl.CrawlDatum。 下面教程给出如何读取SequenceFile的代码。

新建一个类org.apache.nutch.example.InjectorReader

  1. package org.apache.nutch.example;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.FileSystem;
  4. import org.apache.hadoop.fs.Path;
  5. import org.apache.hadoop.io.SequenceFile;
  6. import org.apache.hadoop.io.Text;
  7. import org.apache.nutch.crawl.CrawlDatum;
  8. import java.io.IOException;
  9. /**
  10. * Created by hu on 15-2-9.
  11. */
  12. public class InjectorReader {
  13. public static void main(String[] args) throws IOException {
  14. Configuration conf=new Configuration();
  15. Path dataPath=new Path("/tmp/crawldb/current/part-00000/data");
  16. FileSystem fs=dataPath.getFileSystem(conf);
  17. SequenceFile.Reader reader=new SequenceFile.Reader(fs,dataPath,conf);
  18. Text key=new Text();
  19. CrawlDatum value=new CrawlDatum();
  20. while(reader.next(key,value)){
  21. System.out.println("key:"+key);
  22. System.out.println("value:"+value);
  23. }
  24. reader.close();
  25. }
  26. }

运行结果:

  1. key:http://www.cnbeta.com/
  2. value:Version: 7
  3. Status: 1 (db_unfetched)
  4. Fetch time: Mon Feb 09 13:20:36 CST 2015
  5. Modified time: Thu Jan 01 08:00:00 CST 1970
  6. Retries since fetch: 0
  7. Retry interval: 2592000 seconds (30 days)
  8. Score: 1.0
  9. Signature: null
  10. Metadata:
  11. _maxdepth_=1000
  12. _depth_=1

我们可以看到,程序读出了刚才Inject到crawldb的url,key是url,value是一个CrawlDatum对象,这个对象用来维护爬虫的URL管理信息,我们可以看到一行:

  1. Status: 1 (db_unfetched)

表示当前url为未爬取状态,在后续流程中,爬虫会从crawldb取未爬取的url进行爬取。

完整爬取:

下面给出的是各位最期待的代码,就是如何用Nutch完成一次完整的爬取。官方代码在1.7之前(包括1.7),包含一个Crawl.java,这个代码的main函数可以执行一次完整的爬取,但是从1.7之后就取消了。只保留了使用Linux Shell来调用每个流程,来完成爬取的方法。但是好在取消的Crawl.java修改一下,还是可以使用的。

在爬取之前,我们先修改一下conf/nutch-default.xml中的一个地方,找到:

  1. <property>
  2. <name>http.agent.name</name>
  3. <value></value>
  4. <description>HTTP 'User-Agent' request header. MUST NOT be empty -
  5. please set this to a single word uniquely related to your organization.
  6. NOTE: You should also check other related properties:
  7. http.robots.agents
  8. http.agent.description
  9. http.agent.url
  10. http.agent.email
  11. http.agent.version
  12. and set their values appropriately.
  13. </description>
  14. </property>

中随意添加一个值,修改为:

  1. <property>
  2. <name>http.agent.name</name>
  3. <value>test</value>
  4. <description>HTTP 'User-Agent' request header. MUST NOT be empty -
  5. please set this to a single word uniquely related to your organization.
  6. NOTE: You should also check other related properties:
  7. http.robots.agents
  8. http.agent.description
  9. http.agent.url
  10. http.agent.email
  11. http.agent.version
  12. and set their values appropriately.
  13. </description>
  14. </property>

这个值会在发送http请求时,作为User-Agent字段。

下面给出代码:

  1. package org.apache.nutch.crawl;
  2. import java.util.*;
  3. import java.text.*;
  4. // Commons Logging imports
  5. import org.apache.commons.lang.StringUtils;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.apache.hadoop.fs.*;
  9. import org.apache.hadoop.conf.*;
  10. import org.apache.hadoop.mapred.*;
  11. import org.apache.hadoop.util.Tool;
  12. import org.apache.hadoop.util.ToolRunner;
  13. import org.apache.nutch.parse.ParseSegment;
  14. import org.apache.nutch.indexer.IndexingJob;
  15. //import org.apache.nutch.indexer.solr.SolrDeleteDuplicates;
  16. import org.apache.nutch.util.HadoopFSUtil;
  17. import org.apache.nutch.util.NutchConfiguration;
  18. import org.apache.nutch.util.NutchJob;
  19. import org.apache.nutch.fetcher.Fetcher;
  20. public class Crawl extends Configured implements Tool {
  21. public static final Logger LOG = LoggerFactory.getLogger(Crawl.class);
  22. private static String getDate() {
  23. return new SimpleDateFormat("yyyyMMddHHmmss").format
  24. (new Date(System.currentTimeMillis()));
  25. }
  26. /* Perform complete crawling and indexing (to Solr) given a set of root urls and the -solr
  27. parameter respectively. More information and Usage parameters can be found below. */
  28. public static void main(String args[]) throws Exception {
  29. Configuration conf = NutchConfiguration.create();
  30. int res = ToolRunner.run(conf, new Crawl(), args);
  31. System.exit(res);
  32. }
  33. @Override
  34. public int run(String[] args) throws Exception {
  35. /*种子所在文件夹*/
  36. Path rootUrlDir = new Path("/tmp/urls");
  37. /*存储爬取信息的文件夹*/
  38. Path dir = new Path("/tmp","crawl-" + getDate());
  39. int threads = 50;
  40. /*广度遍历时爬取的深度,即广度遍历树的层数*/
  41. int depth = 2;
  42. long topN = 10;
  43. JobConf job = new NutchJob(getConf());
  44. FileSystem fs = FileSystem.get(job);
  45. if (LOG.isInfoEnabled()) {
  46. LOG.info("crawl started in: " + dir);
  47. LOG.info("rootUrlDir = " + rootUrlDir);
  48. LOG.info("threads = " + threads);
  49. LOG.info("depth = " + depth);
  50. if (topN != Long.MAX_VALUE)
  51. LOG.info("topN = " + topN);
  52. }
  53. Path crawlDb = new Path(dir + "/crawldb");
  54. Path linkDb = new Path(dir + "/linkdb");
  55. Path segments = new Path(dir + "/segments");
  56. Path indexes = new Path(dir + "/indexes");
  57. Path index = new Path(dir + "/index");
  58. Path tmpDir = job.getLocalPath("crawl"+Path.SEPARATOR+getDate());
  59. Injector injector = new Injector(getConf());
  60. Generator generator = new Generator(getConf());
  61. Fetcher fetcher = new Fetcher(getConf());
  62. ParseSegment parseSegment = new ParseSegment(getConf());
  63. CrawlDb crawlDbTool = new CrawlDb(getConf());
  64. LinkDb linkDbTool = new LinkDb(getConf());
  65. // initialize crawlDb
  66. injector.inject(crawlDb, rootUrlDir);
  67. int i;
  68. for (i = 0; i < depth; i++) { // generate new segment
  69. Path[] segs = generator.generate(crawlDb, segments, -1, topN, System
  70. .currentTimeMillis());
  71. if (segs == null) {
  72. LOG.info("Stopping at depth=" + i + " - no more URLs to fetch.");
  73. break;
  74. }
  75. fetcher.fetch(segs[0], threads); // fetch it
  76. if (!Fetcher.isParsing(job)) {
  77. parseSegment.parse(segs[0]); // parse it, if needed
  78. }
  79. crawlDbTool.update(crawlDb, segs, true, true); // update crawldb
  80. }
  81. /*
  82. if (i > 0) {
  83. linkDbTool.invert(linkDb, segments, true, true, false); // invert links
  84. if (solrUrl != null) {
  85. // index, dedup & merge
  86. FileStatus[] fstats = fs.listStatus(segments, HadoopFSUtil.getPassDirectoriesFilter(fs));
  87. IndexingJob indexer = new IndexingJob(getConf());
  88. indexer.index(crawlDb, linkDb,
  89. Arrays.asList(HadoopFSUtil.getPaths(fstats)));
  90. SolrDeleteDuplicates dedup = new SolrDeleteDuplicates();
  91. dedup.setConf(getConf());
  92. dedup.dedup(solrUrl);
  93. }
  94. } else {
  95. LOG.warn("No URLs to fetch - check your seed list and URL filters.");
  96. }
  97. */
  98. if (LOG.isInfoEnabled()) { LOG.info("crawl finished: " + dir); }
  99. return 0;
  100. }
  101. }

运行成功,对网站进行了一个2层的爬取,爬取信息都保存在/tmp/crawl+时间的文件夹中。

  1. 2015-02-09 14:23:17,171 INFO crawl.CrawlDb (CrawlDb.java:update(115)) - CrawlDb update: finished at 2015-02-09 14:23:17, elapsed: 00:00:01
  2. 2015-02-09 14:23:17,171 INFO crawl.Crawl (Crawl.java:run(117)) - crawl finished: /tmp/crawl-20150209142212

有些时候爬虫爬一层就停止了,有几种原因:

  • 1)种子对应的页面大小超过配置的上限,页面被忽略。
  • 2)nutch默认遵循robots协议,有可能robots协议禁止了爬取,不过出现这种情况日志会给出相关信息。
  • 3)网页没有被正确爬取(这种情况少)。

爬很多门户网站时容易出现第一种情况,这种情况只需要找到conf/nutch-default.xml中的:

  1. <property>
  2. <name>http.content.limit</name>
  3. <value>65536</value>
  4. <description>The length limit for downloaded content using the http://
  5. protocol, in bytes. If this value is nonnegative (>=0), content longer
  6. than it will be truncated; otherwise, no truncation at all. Do not
  7. confuse this setting with the file.content.limit setting.
  8. </description>
  9. </property>

将value设置为-1即可

  1. <property>
  2. <name>http.content.limit</name>
  3. <value>-1</value>
  4. <description>The length limit for downloaded content using the http://
  5. protocol, in bytes. If this value is nonnegative (>=0), content longer
  6. than it will be truncated; otherwise, no truncation at all. Do not
  7. confuse this setting with the file.content.limit setting.
  8. </description>
  9. </property>

如果看到日志中有说被robots协议阻拦,修改Fetcher.java的源码,找到:

  1. if (!rules.isAllowed(fit.u.toString())) {
  2. // unblock
  3. fetchQueues.finishFetchItem(fit, true);
  4. if (LOG.isDebugEnabled()) {
  5. LOG.debug("Denied by robots.txt: " + fit.url);
  6. }
  7. output(fit.url, fit.datum, null, ProtocolStatus.STATUS_ROBOTS_DENIED, CrawlDatum.STATUS_FETCH_GONE);
  8. reporter.incrCounter("FetcherStatus", "robots_denied", 1);
  9. continue;
  10. }

将整段代码注释即可。 教程持续更新中。。。。