Java网络爬虫实操(9)
2018-03-17 本文已影响29人
风行者1024
上一篇:Java网络爬虫实操(8)
大家好,上一篇讲到了下载器。这篇介绍爬虫框架NetDiscovery新增的FileDownloader下载器,用于下载二进制流资源(office文档、rar压缩包、图片等)的下载器。
1) 下载图片文件
- 准备好资源的url
- 设置保存到本地的文件夹和文件名
- 设置好下载器
package com.cv4j.netdiscovery.example;
import com.cv4j.netdiscovery.core.Spider;
import com.cv4j.netdiscovery.core.domain.Request;
import com.cv4j.netdiscovery.core.downloader.file.FileDownloadAfterRequest;
import com.cv4j.netdiscovery.core.downloader.file.FileDownloader;
public class DownloadFiles {
public static void main(String[] args) {
//1、文件下载后存储的目录(不存在的话,程序会自动创建的)
String filePath = "D:\\savedir";
//2、指定资源的路径和存储文件名
//也可以参考FileDownloadAfterRequest类自定义parser类,实现下载功能
Request request = new Request("http://cdn2.jianshu.io/assets/web/nav-logo-4c7bbafe27adc892f3046e6978459bac.png");
request.afterRequest(new FileDownloadAfterRequest(filePath, "jianshu.png"));
//3. 构建一个爬虫,设置好下载器FileDownloader
Spider.create()
.request(request)
.downloader(new FileDownloader())
.run();
}
}
下载成功
2) 下载rar文件
package com.cv4j.netdiscovery.example;
import com.cv4j.netdiscovery.core.Spider;
import com.cv4j.netdiscovery.core.domain.Request;
import com.cv4j.netdiscovery.core.downloader.file.FileDownloadAfterRequest;
import com.cv4j.netdiscovery.core.downloader.file.FileDownloader;
public class DownloadFiles {
public static void main(String[] args) {
Request request = new Request("http://jsdx.sc.chinaz.com/Files/DownLoad/moban/201803/zppt2624.rar");
request.afterRequest(new FileDownloadAfterRequest("D:\\savedir", "1.rar"));
Spider.create()
.request(request)
.downloader(new FileDownloader())
.run();
}
}
下载成功
3) 下载多个rar文件
- request(Request... requests) 支持传入多个参数
- 构建request数组
- 传入request方法
- 如果下载的文件比较大,要耐心等待程序运行完。
package com.cv4j.netdiscovery.example;
import com.cv4j.netdiscovery.core.Spider;
import com.cv4j.netdiscovery.core.domain.Request;
import com.cv4j.netdiscovery.core.downloader.file.FileDownloadAfterRequest;
import com.cv4j.netdiscovery.core.downloader.file.FileDownloader;
public class DownloadFiles {
public static void main(String[] args) {
//一次下载3个资源
String[] urls = {"http://jsdx.sc.chinaz.com/Files/DownLoad/moban/201803/zppt2615.rar"
,"http://jsdx.sc.chinaz.com/Files/DownLoad/moban/201803/zppt2639.rar"
,"http://jsdx.sc.chinaz.com/Files/DownLoad/moban/201803/zppt2624.rar"};
String filePath = "D:\\savedir";
//构建Request数组
Request[] requests = new Request[urls.length];
for (int i = 0; i < requests.length; i++) {
String fileName = (i+1)+".rar";
requests[i] = new Request(urls[i])
.afterRequest(new FileDownloadAfterRequest(filePath, fileName));
}
Spider.create()
.request()
.downloader(new FileDownloader())
.run();
}
}
下载成功