开源框架WebCollector抓取图片初试

简介: 开源框架WebCollector抓取图片初试

官网地址:https://github.com/CrawlScript/WebCollector 。这是java版本,如果想要体验Python版本的话请移步 https://github.com/CrawlScript/WebCollector-Python

其它介绍文章

废话不多说,直接进入正题。首先用maven引入相关依赖,目前最新的是2.73-alpha版本

<dependency>
    <groupId>cn.edu.hfut.dmic.webcollector</groupId>
    <artifactId>WebCollector</artifactId>
    <version>2.73-alpha</version>
</dependency>

具体如何使用请看下面示例代码,用来抓取网站的图片,具体哪个网站不太方便给出来,大家自行尝试。

import cn.edu.hfut.dmic.webcollector.model.CrawlDatums;
import cn.edu.hfut.dmic.webcollector.model.Page;
import cn.edu.hfut.dmic.webcollector.plugin.berkeley.BreadthCrawler;
import cn.edu.hfut.dmic.webcollector.util.ExceptionUtils;
import cn.edu.hfut.dmic.webcollector.util.FileUtils;
import cn.edu.hfut.dmic.webcollector.util.MD5Utils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;

/**
 * 继承 BreadthCrawler(广度爬虫)
 * BreadthCrawler 是 WebCollector 最常用的爬取器之一
 *
 * @author hu
 */
public class DemoCrawler extends BreadthCrawler {
   
    File baseDir = new File("images");

    /**
     * 构造一个基于伯克利DB的爬虫
     * 伯克利DB文件夹为crawlPath,crawlPath中维护了历史URL等信息
     * 不同任务不要使用相同的crawlPath
     * 两个使用相同crawlPath的爬虫并行爬取会产生错误
     *
     * @param crawlPath 伯克利DB使用的文件夹
     */
    public DemoCrawler(String crawlPath) {
   
        //设置是否自动解析网页内容
        super(crawlPath, true);

        //只有在autoParse和autoDetectImg都为true的情况下
        //爬虫才会自动解析图片链接
        //getConf().setAutoDetectImg(true);

        //如果使用默认的Requester,需要像下面这样设置一下网页大小上限
        //否则可能会获得一个不完整的页面
        //下面这行将页面大小上限设置为10M
        //getConf().setMaxReceiveSize(1024 * 1024 * 10);

        //添加种子URL
        addSeed("http://www.xxx.com");
        //限定爬取范围
        addRegex("http://image.xxx.com/.*");
        addRegex("-.*#.*");
        addRegex("-.*\\?.*");
        //设置线程数
        setThreads(10);
    }

    @Override
    public void visit(Page page, CrawlDatums next) {
   
        //根据http头中的Content-Type信息来判断当前资源是网页还是图片
        String contentType = page.contentType();
        if (contentType == null) {
   
            return;
        } else if (contentType.contains("html")) {
   
            //如果是网页,则抽取其中包含图片的URL,放入后续任务
            Elements imgs = page.select("img[src]");
            for (Element img : imgs) {
   
                String imgSrc = img.attr("abs:src");
                if (imgSrc.indexOf("thumb") < 0) {
   
                    next.add(imgSrc);
                }
            }
        } else if (contentType.startsWith("image")) {
   
            //如果是图片,直接下载
            String extensionName = contentType.split("/")[1];
            try {
   
                byte[] image = page.content();
                //限制文件大小 10k
                if (image.length < 10240) {
   
                    return;
                }
                //根据图片MD5生成文件名
                String fileName = String.format("%s.%s", MD5Utils.md5(image), extensionName);
                File imageFile = new File(baseDir, fileName);
                FileUtils.write(imageFile, image);
                System.out.println("保存图片 " + page.url() + " 到 " + imageFile.getAbsolutePath());
            } catch (Exception e) {
   
                ExceptionUtils.fail(e);
            }
        }
    }

    // 主要解决下载图片出现403的问题
    // 自定义的请求插件
    // 可以自定义User-Agent和Cookie
    public static class MyRequester extends OkHttpRequester {
   
        String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36";

        // 每次发送请求前都会执行这个方法来构建请求
        @Override
        public Request.Builder createRequestBuilder(CrawlDatum crawlDatum) {
   
            // 这里使用的是OkHttp中的Request.Builder
            // 可以参考OkHttp的文档来修改请求头
            return super.createRequestBuilder(crawlDatum)
                   .removeHeader("User-Agent")  //移除默认的UserAgent
                   .addHeader("Referer", "http://www.xxx.com")
                   .addHeader("User-Agent", userAgent);
        }
    }

    public static void main(String[] args) throws Exception {
   
        //crawl为日志目录
        DemoCrawler demoImageCrawler = new DemoCrawler("crawl");
        demoImageCrawler.setRequester(new MyRequester());
        //设置为断点爬取,否则每次开启爬虫都会重新爬取
        demoImageCrawler.setResumable(true);
        //爬取深度
        demoImageCrawler.start(5);
    }
}

示例代码参考了以下来源,稍微优化了一下
http://datahref.com/archives/132

相关文章
|
JavaScript
在vue3中使用markdown编辑器
在vue3中使用markdown编辑器
在vue3中使用markdown编辑器
|
11月前
|
人工智能
人工智能管理体系解读(一)
ISO/IEC 42001 标准旨在指导组织建立、实施、维护和持续改进人工智能管理体系,强调负责任地使用、开发和运营人工智能系统,适用于所有采用AI系统的组织。标准涵盖了道德问题、法律法规遵从性、持续改进等方面,帮助组织提升运营效率、加强风险管理并提高声誉。
230 1
|
9月前
|
存储 监控 算法
解决方案评测:多模态数据信息提取
解决方案评测:多模态数据信息提取
241 8
|
Perl
awk通过 system() 函数调用其他命令获取输出
awk通过 system() 函数调用其他命令获取输出
702 7
|
10月前
|
监控 安全 网络安全
|
11月前
|
存储 关系型数据库 MySQL
四种数据库对比MySQL、PostgreSQL、ClickHouse、MongoDB——特点、性能、扩展性、安全性、适用场景
四种数据库对比 MySQL、PostgreSQL、ClickHouse、MongoDB——特点、性能、扩展性、安全性、适用场景
|
数据采集 存储 JSON
推荐3款自动爬虫神器,再也不用手撸代码了
推荐3款自动爬虫神器,再也不用手撸代码了
846 4
|
负载均衡 监控 算法
云计算 - 负载均衡SLB方案全解与实战
云计算 - 负载均衡SLB方案全解与实战
630 0
|
监控 UED 开发者
通过云拨测对指定网页进行网页性能监测
本实验将通过云拨测对指定服务器进行网页性能监测,评估网站服务质量和用户体验。
439 72