WebCollector爬虫爬取一个或多个网站

定义一个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
-----------------------------


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值