java 爬虫:开源java爬虫 swing工具 Imgraber
1实现点:
- 1.返回给定URL网页内,所有图像url list
- 2.返回给定URL网页内,自动生成图像文件路径.txt 文件
- 3.返回给定URL网页内,下载txt文件指定的图片url,并将所有图像保存在 ./img文件夹下
- 4.实现简易swing 界面,有空再改造
2基于开源jsoup实现,鸣谢!
效果




github
package himi.crawler;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
/**
*
* @ClassName: ImgTool
* @Description:IMG tool ,请先赋值URL 获取指定ULR的某个网页里面
* 1.返回所有图像url list
* 2.图像文件夹路径.txt
* 3.所有图像保存在img文件夹里面
* @author penny
* @date 2018年3月7日 下午10:07:49
*
*/
public class ImgTool {
// 参数域
/** 指定URL */
public static String URL = "https://www.oschina.net";
private int imgNumbs = 0;
public static List<String> downloadMsg=new ArrayList<String>();
public String imgUrlTxt = "imgURLs.txt";
public static String regex= "^((https|http|ftp|rtsp|mms)?://)"
+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
+ "(([0-9].)[0-9]" // IP形式的URL- 199.194.52.184
+ "|" // 允许IP和DOMAIN(域名)
+ "([0-9a-z_!~*'()-]+.)*" // 域名-
+ "([0-9a-z][0-9a-z-])?[0-9a-z]." // 二级域名
+ "[a-z])" // first level domain- .com or .museum
+ "(:[0-9])?" // 端口- :80
+ "((/?)|" // a slash isn't required if there is no file name
+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
private ImgTool() {
};
private static ImgTool instance = new ImgTool();
/** 获取ImgTool 单例 */
public static ImgTool getInstance() {
return instance;
}
public List<String> getURLs() {
return getURLs(null);
}
public boolean isURL(String str) {
if(StringUtil.isBlank(str)){
return false;
}else{
// String regex = "^(?:https?://)?[\\w]{1,}(?:\\.?[\\w]{1,})+[\\w-_/?&=#%:]*$";
// String regex = "^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
if(matcher.matches()){
return true;
}else{
return false;
}
}};
/***
* @Title: getURLs
* @Description: 给定cssQuery对象
* @param @param cssQuery HTML中的CSS(或者 JQuery)选择器语法,更多详细用法见Jsoup介绍 < a
* href="https://jsoup.org/apidocs/org/jsoup/select/Selector.html"
* ></a>
* @param @return List
* @throws
*
*/
public List<String> getURLs(String cssQuery) {
List<String> urls = null;
Document doc;
Elements imgElements ;
if (!isURL(URL)) {
return null;
}
if(StringUtil.isBlank(cssQuery)){
cssQuery="img";
}
try {
doc = Jsoup.connect(URL).get();
} catch (IOException e) {
e.printStackTrace();
return null;
}
if(doc==null)return null;
imgElements = doc.select(cssQuery);
urls = new ArrayList<String>();
for (Object eleObj : imgElements) {
//"(https?|ftp|http)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]"
Pattern pattern = Pattern.compile("(https?|http)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]");
Matcher matcher = pattern.matcher(eleObj.toString());
if (matcher.find()) {
String url = matcher.group();
urls.add(url);
}
}
imgNumbs = imgElements.size();
return urls;
}
/**
*
* @Title: createImgURLTxt
* @Description:
* @param @param cssQuery:默认使用img HTML中的CSS(或者 JQuery)选择器语法,更多详细用法见Jsoup介绍 <
* a href="https://jsoup.org/apidocs/org/jsoup/select/Selector.html">
* </a>
* @throws 生成imgURLs.txt
*/
public String createImgURLTxt(String cssQuery) {
long start = System.currentTimeMillis();
List<String> urls;
urls = getURLs(cssQuery);
BufferedWriter os = null;
File urlsFiles = new File("imgURLs.txt");
if(urlsFiles.exists()){
try {
urlsFiles.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os = new BufferedWriter(new FileWriter(urlsFiles));
if(urls==null)return null;
for (int i = 0; i < urls.size(); i++) {
os.write(urls.get(i) + "\n");
}
String result = "执行完毕,生成imgURLs.txt,耗时"
+ (System.currentTimeMillis() - start) / 1000 + "s";
System.out.println(result);
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (os != null)
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
*
* @Title: createImgs
* @Description:
* @param @param cssQuery
* @param @throws IOException
* @throws
*/
public void createImgs(String cssQuery) throws IOException {
long startTime = System.currentTimeMillis();
downloadMsg.add("Your images is downloading ");
BufferedReader br = null;
OutputStream out = null;
InputStream in = null;
ArrayList<String> imgList = null;
HttpURLConnection con = null;
String url; //待下载文件url
int fileSize = 0; //单个文件大小
int totalFileNum=0; //总文件数
int downLoadFileNum=0; //已下载文件
long totalTime=0; //总耗时/s
long singleTime=0; //单个文件耗时/ms
br = new BufferedReader(new FileReader(imgUrlTxt));
imgList = new ArrayList<String>();
while ((url = br.readLine()) != null) {
imgList.add(url);
}
downLoadFileNum=totalFileNum= imgList.size();
downloadMsg.add("总文件数"+(totalFileNum));
for (String listUrl : imgList) {
startTime = System.currentTimeMillis();
String fileName = listUrl.substring(listUrl.lastIndexOf('/') + 1);// 截取文件名
URL imgUrl = new URL(listUrl.trim());
if (con != null)
con.disconnect();
con = (HttpURLConnection) imgUrl.openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setConnectTimeout(1000 * 30);
con.setReadTimeout(1000 * 30);
fileSize = con.getContentLength();
con.connect();
try {
in = con.getInputStream();
File file = new File("img" + File.separator, fileName);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
out = new BufferedOutputStream(new FileOutputStream(file));
int len = 0;
byte[] buff = new byte[1024 * 1024];
while ((len = new BufferedInputStream(in).read(buff)) != -1) {
out.write(buff, 0, len);
}
out.flush();
downLoadFileNum--;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
if (in != null)
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
if (out != null)
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
singleTime=System.currentTimeMillis() - startTime;
totalTime+=singleTime;
downloadMsg.add("文件名" + fileName + " 文件大小" + fileSize
+" 未下载文件数"+(downLoadFileNum)
+" 下载耗时"+ singleTime + "ms" );
System.out.println(downloadMsg.get(downloadMsg.size()-1));
}
}
downloadMsg.add("总耗时"+totalTime/1000+"s");
}
/**
* @throws IOException
*
* @Title: main
* @Description: test
* @param @param args
* @throws
*/
public static void main(String[] args) throws IOException {
ImgTool img = ImgTool.getInstance();
img.createImgURLTxt("img");
List<String> urls = img.getURLs("img");
for (Object str : urls) {
System.out.println(str.toString());
}
img.createImgs(null);
}
}
java 爬虫:开源java爬虫 swing工具 Imgraber的更多相关文章
- 基于 Java 的开源网络爬虫框架 WebCollector
原文:https://www.oschina.net/p/webcollector
- 【转】44款Java 网络爬虫开源软件
原帖地址 http://www.oschina.net/project/lang/19?tag=64&sort=time 极简网络爬虫组件 WebFetch WebFetch 是无依赖极简网页 ...
- 不会python?那就换一种姿势爬虫!Java爬虫技术总结
-本博客为原创内容,转载需注明本人- 前几天有个师妹将要毕业,需要准备毕业论文,但是论文调研需要数据资料,上知网一查,十几万条数据!指导老师让她手动copy收集,十几万的数据手动copy要浪费多少时间 ...
- 用java实现新浪爬虫,代码完整剖析(仅针对当前SinaSignOn有效)
先来看我们的web.xml文件,如下 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application ...
- 7 款开源 Java 反编译工具
今天我们要来分享一些关于Java的反编译工具,反编译听起来是一个非常高上大的技术词汇,通俗的说,反编译是一个对目标可执行程序进行逆向分析,从而得到原始代码的过程.尤其是像.NET.Java这样的运行在 ...
- WEKA,一个开源java的数据挖掘工具
开始研究WEKA,一个开源java的数据挖掘工具. HS沉寂这么多天,谁知道偏偏在我申请离职的时候给我安排了个任务,哎,无语. 于是,今天看了一天的Weka. 主要是看了HS提供的三个文章(E文,在g ...
- 7款开源Java反编译工具
今天我们要来分享一些关于Java的反编译工具,反编译听起来是一个非常高上大的技术词汇,通俗的说,反编译是一个对目标可执行程序进行逆向分析,从而得到原始代码的过程.尤其是像.NET.Java这样的运行在 ...
- Java 图片爬虫,java打包jar文件
目录 1. Java 图片爬虫,制作 .jar 文件 spider.java 制作 jar 文件 添加执行权限 1. Java 图片爬虫,制作 .jar 文件 spider.java spider.j ...
- Arthas Alibaba 开源 Java 诊断工具
Arthas 用户文档 English Docs Arthas(阿尔萨斯) 能为你做什么? Arthas 是Alibaba开源的Java诊断工具,深受开发者喜爱. 当你遇到以下类似问题而束手无策时,A ...
随机推荐
- CRM 线索 客户 统称为 资源 客户服务管理篇 销售易
线索 客户 统称为 资源 - 国内版 Binghttps://cn.bing.com/search?FORM=U227DF&PC=U227&q=%E7%BA%BF%E7%B4%A2+% ...
- Tomcat 8.5.x RedisSessionManager show:Caused by: java.lang.NoSuchMethodError: com.crimsonhexagon.rsm.
Caused by: java.lang.NoSuchMethodError: com.crimsonhexagon.rsm.RedisSessionManager.getMaxInactiveInt ...
- [转]java生成 excel 并导出文件
原文:https://blog.csdn.net/xunwei0303/article/details/53213130 目前,比较常用的实现Java导入.导出Excel的技术有两种Jakarta P ...
- Centos7搭建OpenNebula云平台
OpenNebula概述 OpenNebula是专门为云计算打造的开源系统,用户可以使用Xen.KVM.VMware等虚拟化软件一起打造企业云.利用OpenNebula可以轻松构建私有云.混合云.公开 ...
- openresty开发系列17--lua中的正则表达式
与其他脚本语言不同的是,Lua并不使用POSIX规范的正则表达式[4](也写作regexp)来进行模式匹配.主要的原因出于程序大小方面的考虑:实现一个典型的符合POSIX标准的regexp大概需要40 ...
- Python3基础 内置函数 hash
Python : 3.7.3 OS : Ubuntu 18.04.2 LTS IDE : pycharm-community-2019.1.3 ...
- 微信小程序与Html交互
微信小程序与H5页面交互 https://www.jianshu.com/p/22e951d83841
- hadoop记录-[Flink]Flink三种运行模式安装部署以及实现WordCount(转载)
[Flink]Flink三种运行模式安装部署以及实现WordCount 前言 Flink三种运行方式:Local.Standalone.On Yarn.成功部署后分别用Scala和Java实现word ...
- 【k8s 硬盘监控】prometheus grafana
设置监控哪块盘: https://www.bountysource.com/issues/50160777-disk-space-usage-depcited-in-grafana-correct h ...
- C# 利用bat文件轻松创建windos 服务
最近,一个项目需要一个后台服务,定时去读取数据,这是直接创建一个bat文件,双击执行就可以了,为了省事哦 主要分两个步奏 1.创建windows服务的应用程序.这一点不做过多讲解.网上有太多的例子 2 ...