java爬虫抓取动态网页(体验Python版本的话-alpha版本示例代码介绍)
优采云 发布时间: 2021-09-27 21:26java爬虫抓取动态网页(体验Python版本的话-alpha版本示例代码介绍)
官方网站地址:。这是Java版本。如果您想体验python版本,请继续
其他介绍文章
不要说太多废话。直截了当地说。首先,使用Maven引入相关的依赖关系。目前,最新版本为2.73 alpha
cn.edu.hfut.dmic.webcollector
WebCollector
2.73-alpha
请参阅下面的示例代码了解如何使用它。它用于捕捉网站的图片。这网站不方便发放,我们自己试试吧
<p>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")