Java jsoup爬取图片
是的,Java也可以做网络爬虫,不仅可以爬静态网页的图片,也可以爬动态网页的图片,比如采用Ajax技术进行异步加载的百度瀑布流。
以前有写过用Java进行百度图片的抓取,但只能抓取到第一二页,本博文则对此问题进行了深入研究,提出了另外一种思路解决问题。我的思路是这样的:以前人们总认为既然百度瀑布流是采用JavaScript进行异步加载的,那么爬取图片至少要有一个模拟浏览器,比如Java领域中的无界面浏览器工具HtmlUnit,但后来我发现其实Jsoup也是可以的,只要用Jsoup去向百度服务器发送Ajax请求就行了,幸运的是我在观察百度图片的ajax请求时还真发现有两个类型的请求方式:avatarjson和acjson,实验告诉我们第一种请求方式已经几乎可以满足我们的所有需求。
本博文所实现的效果是:根据输入的多个关键字,可以按定制的页数把各自关键字的搜索结果下载到本地文件夹中。具体如下所示:
废话不多说,程序满上------->
- package com.kendy.spider;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import org.apache.commons.lang3.StringEscapeUtils;
- import org.jsoup.Jsoup;
- import org.jsoup.nodes.Document;
- // 爬取百度图片
- public class JsoupBaidu2 {
- public static void main(String[] args) throws Exception{
- String downloadPath = "C:\\Users\\Kendy\\Desktop\\中国明星图";
- List<String> list = nameList("凯莉·布鲁克 詹妮弗·洛佩兹 碧昂斯·诺里斯");
- getPictures(list,1,downloadPath); //1代表下载一页,一页一般有30张图片
- }
- public static void getPictures(List<String> keywordList, int max,String downloadPath) throws Exception{ // key为关键词,max作为爬取的页数
- String gsm=Integer.toHexString(max)+"";
- String finalURL = "";
- String tempPath = "";
- for(String keyword : keywordList){
- tempPath = downloadPath;
- if(!tempPath.endsWith("\\")){
- tempPath = downloadPath+"\\";
- }
- tempPath = tempPath+keyword+"\\";
- File f = new File(tempPath);
- if(!f.exists()){
- f.mkdirs();
- }
- int picCount = 1;
- for(int page=0;page<=max;page++) {
- sop("正在下载第"+page+"页面");
- Document document = null;
- try {
- String url ="http://image.baidu.com/search/avatarjson?tn=resultjsonavatarnew&ie=utf-8&word="+keyword+"&cg=star&pn="+page*30+"&rn=30&itg=0&z=0&fr=&width=&height=&lm=-1&ic=0&s=0&st=-1&gsm="+Integer.toHexString(page*30);
- sop(url);
- document = Jsoup.connect(url).data("query", "Java")//请求参数
- .userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)")//设置urer-agent get();
- .timeout(5000)
- .get();
- String xmlSource = document.toString();
- xmlSource = StringEscapeUtils.unescapeHtml3(xmlSource);
- sop(xmlSource);
- String reg = "objURL\":\"http://.+?\\.jpg";
- Pattern pattern = Pattern.compile(reg);
- Matcher m = pattern.matcher(xmlSource);
- while (m.find()) {
- finalURL = m.group().substring(9);
- sop(keyword+picCount+++":"+finalURL);
- download(finalURL,tempPath);
- sop(" 下载成功");
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- sop("下载完毕");
- delMultyFile(downloadPath);
- sop("已经删除所有空图");
- }
- public static void delMultyFile(String path){
- File file = new File(path);
- if(!file.exists())
- throw new RuntimeException("File \""+path+"\" NotFound when excute the method of delMultyFile()....");
- File[] fileList = file.listFiles();
- File tempFile=null;
- for(File f : fileList){
- if(f.isDirectory()){
- delMultyFile(f.getAbsolutePath());
- }else{
- if(f.length()==0)
- sop(f.delete()+"---"+f.getName());
- }
- }
- }
- public static List<String> nameList(String nameList){
- List<String> arr = new ArrayList<>();
- String[] list;
- if(nameList.contains(","))
- list= nameList.split(",");
- else if(nameList.contains("、"))
- list= nameList.split("、");
- else if(nameList.contains(" "))
- list= nameList.split(" ");
- else{
- arr.add(nameList);
- return arr;
- }
- for(String s : list){
- arr.add(s);
- }
- return arr;
- }
- public static void sop(Object obj){
- System.out.println(obj);
- }
- //根据图片网络地址下载图片
- public static void download(String url,String path){
- //path = path.substring(0,path.length()-2);
- File file= null;
- File dirFile=null;
- FileOutputStream fos=null;
- HttpURLConnection httpCon = null;
- URLConnection con = null;
- URL urlObj=null;
- InputStream in =null;
- byte[] size = new byte[1024];
- int num=0;
- try {
- String downloadName= url.substring(url.lastIndexOf("/")+1);
- dirFile = new File(path);
- if(!dirFile.exists() && path.length()>0){
- if(dirFile.mkdir()){
- sop("creat document file \""+path.substring(0,path.length()-1)+"\" success...\n");
- }
- }else{
- file = new File(path+downloadName);
- fos = new FileOutputStream(file);
- if(url.startsWith("http")){
- urlObj = new URL(url);
- con = urlObj.openConnection();
- httpCon =(HttpURLConnection) con;
- in = httpCon.getInputStream();
- while((num=in.read(size)) != -1){
- for(int i=0;i<num;i++)
- fos.write(size[i]);
- }
- }
- }
- }catch (FileNotFoundException notFoundE) {
- sop("找不到该网络图片....");
- }catch(NullPointerException nullPointerE){
- sop("找不到该网络图片....");
- }catch(IOException ioE){
- sop("产生IO异常.....");
- }catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- fos.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
Java jsoup爬取图片的更多相关文章
- jsoup爬取图片到本地
因为项目需求,需要车辆品牌信息和车系信息,昨天用一天时间研究了jsoup爬取网站信息.项目是用maven+spring+springmvc+mybatis写的. jsoup开发指南地址:http:// ...
- java 利用jsoup 爬取知乎首页问题
今天学了下java的爬虫,首先要下载jsoup的包,然后导入,导入过程:首先右击工程:Build Path ->configure Build Path,再点击Add External JARS ...
- Jsoup爬取带登录验证码的网站
今天学完爬虫之后想的爬一下我们学校的教务系统,可是发现登录的时候有验证码.因此研究了Jsoup爬取带验证码的网站: 大体的思路是:(需要注意的是__VIEWSTATE一直变化,所以我们每个页面都需要重 ...
- [python爬虫] 爬取图片无法打开或已损坏的简单探讨
本文主要针对python使用urlretrieve或urlopen下载百度.搜狗.googto(谷歌镜像)等图片时,出现"无法打开图片或已损坏"的问题,作者对它进行简单的探讨.同时 ...
- jsoup爬取某网站安全数据
jsoup爬取某网站安全数据 package com.vfsd.net; import java.io.IOException; import java.sql.SQLException; impor ...
- Java实现爬取京东手机数据
Java实现爬取京东手机数据 最近看了某马的Java爬虫视频,看完后自己上手操作了下,基本达到了爬数据的要求,HTML页面源码也刚好复习了下,之前发布两篇关于简单爬虫的文章,也刚好用得上.项目没什么太 ...
- [java] jsoup使用简介-汇率换算器实现-插曲2
[java] jsoup使用简介-汇率换算器实现-插曲2 // */ // ]]> [java] jsoup使用简介-汇率换算器实现-插曲2 Table of Contents 1 系列文章 ...
- python如何使用request爬取图片
下面是代码的简单实现,变量名和方法都是跑起来就行,没有整理,有需要的可以自己整理下: image2local: import requests import time from lxml import ...
- json-lib-2.4-jdk15.jar所需全部JAR包.rar java jsoup解析开彩网api接口json数据实例
json-lib-2.4-jdk15.jar所需全部JAR包.rar java jsoup解析开彩网api接口json数据实例 json-lib-2.4-jdk15.jar所需全部JAR包.rar ...
随机推荐
- C语言老司机学Python (一)
Python 版本:3.6.4 参考网上教程:http://www.runoob.com/python3/python3-basic-syntax.html 开始了啊. 干咱们这行的老规矩,学新语言的 ...
- 解析setTimeout时间设置为0
1.开胃菜,setTimeout为何物 首先看一下w3school上面对于setTimeout的解释 setTimeout(fn,millisec) 方法用于在指定的毫秒数后调用函数或计算表达式. 很 ...
- probabilistic robotics_bayes filter
贝叶斯滤波 执行测量后的后验概率: 执行测量前的先验概率: 执行测量后的后验概率推导 根据式2.23的推导方式 可推出 假定xt是complete,即xt可以完全决定测量结果,那么则有2.56式: 带 ...
- ubuntu 14.04 分辨率调整 -- xrandr命令
问题描述: 自己在安装ubuntu-kylin 14.04 TLS系统成功后,在调整分辨率的时候(系统设置--显示)发现分辨率的选项只有1024x768以及800x600两个选项,而台式机的外接显示屏 ...
- android DecorView深入理解
开发中,通常都是在onCreate()中调用setContentView(R.layout.custom_layout)来实现想要的页面布局.页面都是依附在窗口之上的,而DecorView即是窗口最顶 ...
- windows2003服务器系统日志:查看电脑远程登录记录
控制面板>>管理工具>>事件查看器>>选择安全性再点工具栏目中查看>>筛选>>事件ID填528进行过滤,时间你看是多久,双击查看之后就可以找 ...
- CF384 div2 E. Vladik and cards
题意 给你一个的排列,求一个满足条件的最长子序列 每种数字的差小于等于,并且每种数字之内是连续的 解法 首先单纯认为用肯定不行的 所以应该考虑二分答案(所求长度具有二分性) 再用dp判断是否可行,这个 ...
- Win Form不能响应键盘事件
在窗体属性中,将KeyPreview设置为true
- Jenkins + Github持续集成构建Docker容器,维基百科&人工自能(AI)模块
本文分两部分,第一部分是手动计划任务的方式构建Github上的Docker程序,第二部分是用Github webhook Trigger一个自动构建任务. Jenkins采用2.5版本Docker采用 ...
- 【BZOJ1007】水平可见直线(单调栈)
[BZOJ1007]水平可见直线(单调栈) 题解 Description 在xoy直角坐标平面上有n条直线L1,L2,...Ln,若在y值为正无穷大处往下看,能见到Li的某个子线段,则称Li为 可见的 ...