现在的位置: 首页 > 综合 > 正文

用WebCollector爬取网站的图片

2017年11月11日 ⁄ 综合 ⁄ 共 1191字 ⁄ 字号 评论关闭

用WebCollector爬取整站图片,只需要遍历整站页面,然后将URL为.jpg、gif的页面(文件)保存到本地即可。

例如我们爬取一个美食网站,获取里面所有的图片:

import cn.edu.hfut.dmic.webcollector.crawler.BreadthCrawler;
import cn.edu.hfut.dmic.webcollector.model.Page;
import cn.edu.hfut.dmic.webcollector.util.FileUtils;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;

/**
 * 用WebCollector爬虫爬取整站图片
 */
public class PicCrawler extends BreadthCrawler{

    /*用一个整数,不断自增,来作为下载的图片的文件名*/
    AtomicInteger id=new AtomicInteger(0);

    @Override
    public void visit(Page page) {
        
        /*不处理非jpg的网页/文件*/
        if(!Pattern.matches(".*jpg$",page.getUrl())){
            return;
        }
        /*将图片内容保存到文件,page.getContent()获取的是文件的byte数组*/
        try {
            FileUtils.writeFileWithParent("download/"+id.incrementAndGet()+".jpg",page.getContent());
            System.out.println("download:"+page.getUrl());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        PicCrawler crawler=new PicCrawler();
        crawler.addSeed("http://www.meishij.net/");
        crawler.addRegex("http://.*meishij.net/.*");
        crawler.setThreads(50);
        crawler.start(10);
    }
}

代码将网站图片保存到了工程下面的download文件夹中:

WebCollector爬虫官网:https://github.com/CrawlScript/WebCollector

WebCollector文档:http://www.brieftools.info/document/webcollector/

技术讨论群:250108697

抱歉!评论已关闭.