Nutch插件机制非常好,它给我们提供了爬取各个步骤的接口,使我们能够自己定制想要的功能,关于nutch插件编写的例子请看我
之前的一篇文章,这里主要介绍下如何通过插件方式对爬取的内容进行过滤。我把需要过滤的内容以关键词的形式存储在数据库中
,爬取时从数据库中提取到内存中,当建立索引时,如果网页包含有需要过滤的内容,则丢弃该网页。要实现索引过滤就必须实现
org.apache.nutch.indexer.IndexingFilter这个接口,参考代码如下:
private Configuration conf;
public ContentFilter() {
}
/***
* 过滤包含过滤词的网页,如果包含过滤词,则返回null
*/
public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
CrawlDatum datum, Inlinks inlinks) throws IndexingException {
String content = parse.getText();//取得网页内容
String title = parse.getData().getTitle();//取得网页标题
List<String> filterWords = FilterWord.getFilterWords();//静态变量存储过滤词
for(int i = 0; i < filterWords.size(); i++ ){
if (content.contains(filterWords.get(i))) {
doc = null;
}
if (title.contains(filterWords.get(i))) {
doc = null;
}
}
return doc;
}
public void setConf(Configuration conf) {
this.conf = conf;
}
public Configuration getConf() {
return this.conf;
}
public void addIndexBackendOptions(Configuration conf) {
this.conf = conf;
}
}