WebCollector2.X 爬蟲
WebCollector介紹:
WebCollector是一個無須配置、便於二次開發的JAVA爬蟲框架(內核),它提供精簡的的API,只需少量代碼即可實現一個功能強大的爬蟲。WebCollector-Hadoop是WebCollector的Hadoop版本,支持分佈式爬取。
WebCollector2.X下載
碼雲地址: 點擊這裏
快速上手:
Maven搭建開發環境:
<span style="white-space:pre"> </span><!-- 加入爬蟲的Jar包 -->
<dependency>
<groupId>cn.edu.hfut.dmic.webcollector</groupId>
<artifactId>WebCollector</artifactId>
<version>2.09</version>
</dependency>
測試代碼:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.regex.Pattern;
import cn.edu.hfut.dmic.webcollector.crawler.BreadthCrawler;
import cn.edu.hfut.dmic.webcollector.model.Links;
import cn.edu.hfut.dmic.webcollector.model.Page;
public class BaiDu_Demo3 extends BreadthCrawler {
public BaiDu_Demo3(String crawlPath, boolean autoParse) {
super(crawlPath, autoParse);
}
@Override
public void visit(Page page, Links nextLinks) {
/**
*
* 爬蟲的核心代碼
*
*/
if (Pattern.matches("http://baike.baidu.com/view/.*", page.getUrl())) {
// String title =
// page.getDoc().select("div[class=article_title]").text();
/**
* 處理作者 每個作者 指定一個文件夾
*/
String title = page.getDoc().select("input[id=query]").val();
/**
* 文件輸出到指定位置
*/
Writer out = null;
File file = new File("d://WebCollecter//Baidu文庫//" + title + ".html");
BufferedWriter bw = null;
try {
out = new FileWriter(file);
bw = new BufferedWriter(out);
String context = page.getHtml();
bw.write(context);
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bw.flush();
bw.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
BaiDu_Demo3 crawler = new BaiDu_Demo3("crawler", true);
// 添加種子URL
crawler.addSeed("http://baike.baidu.com/view/1.htm");
// 限定爬取範圍
crawler.addRegex("http://baike.baidu.com/view/.*.htm");
crawler.setThreads(300);
try {
System.out.println("開始爬....");
crawler.start(2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Demo最後效果 將網頁抓取並輸出爲 HTML文件!!!