定义一个MyCrawler类,继承BreadthCrawler,来完成一个爬虫,对合肥工业大学官网和新华网进行爬取。
对于一个最简单的爬虫,有2个东西是必备的:
1)种子
2)正则约束
3)对每个页面的自定义操作(BreadthCrawler默认的visit方法是将网页保存到文件夹,建议覆盖,改成自己的自定义操作)
import cn.edu.hfut.dmic.webcollector.crawler.BreadthCrawler; import cn.edu.hfut.dmic.webcollector.model.Page; public class MyCrawler extends BreadthCrawler{ /*在visit方法里定义自己的操作*/ @Override public void visit(Page page) { System.out.println("URL:"+page.getUrl()); System.out.println("Content-Type:"+page.getResponse().getContentType()); System.out.println("Code:"+page.getResponse().getContentType()); System.out.println("-----------------------------"); } public static void main(String[] args) throws Exception{ MyCrawler crawler=new MyCrawler(); /*配置爬取合肥工业大学网站*/ crawler.addSeed("http://www.hfut.edu.cn/ch/"); crawler.addRegex("http://.*hfut\\.edu\\.cn/.*"); /*配置爬取新华网*/ crawler.addSeed("http://www.xinhuanet.com/"); crawler.addRegex("http://.*xinhuanet\\.com/.*"); crawler.start(5); } }
运行结果:
2014-10-03 22:19:11 INFO default - fetch http://jpkc.hfut.edu.cn/ URL:http://jpkc.hfut.edu.cn/ Content-Type:text/html; charset=GB2312 Code:text/html; charset=GB2312 ----------------------------- 2014-10-03 22:19:11 INFO default - fetch http://www.he.xinhuanet.com/ URL:http://www.he.xinhuanet.com/ Content-Type:text/html Code:text/html ----------------------------- 2014-10-03 22:19:11 INFO default - fetch http://www.sh.xinhuanet.com/ URL:http://www.sh.xinhuanet.com/ Content-Type:text/html Code:text/html ----------------------------- 2014-10-03 22:19:11 INFO default - fetch http://www.jx.xinhuanet.com/ URL:http://www.jx.xinhuanet.com/ Content-Type:text/html Code:text/html -----------------------------