java获取百度图片学习记录

主要用到的jar包

        <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId></dependency>

分析百度加载url,每次请求加载30张图片,主要有参数pn控制,gsm为pn的16进制,最后是时间戳,搜索内容有queryWord控制

https://image.baidu.com/search/acjson?tn=resultjson_com&logid=7312553249612451609&ipn=rj&ct=201326592&is=&fp=result&fr=&word=%E7%BE%8E%E6%99%AF&queryWord=%E7%BE%8E%E6%99%AF&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=&copyright=&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&expermode=&nojc=&isAsync=&pn=30&rn=30&gsm=1e&1646700092850=

可以写一个实体类用来设置url

public class PageUrl {private String queryWord; private int pn; private String gsm; public PageUrl(String queryWord, int pn) {// 对查询关键字进行url编码try {this.queryWord = URLEncoder.encode(queryWord, "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}this.pn = pn;this.gsm = Integer.toHexString(pn);}// pn 和 gsm 应该是一起变化的public void setPn(int pn) {this.pn = pn;this.gsm = Integer.toHexString(pn);}@Overridepublic String toString() {return "http://image.baidu.com/search/acjsontn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord="+ queryWord + "&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=&latest=&copyright=&word="+ queryWord + "&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&force=&pn="                                                          + pn+ "&rn=30&gsm=" + gsm + "&" + new Date().getTime() + "=";}
}

编写实现类

public class PicSpider {public void crawlePicture(String queryWord, int page) throws Exception {if (page < 1) {throw new Exception("page set error.");}PageUrl pageUrl = new PageUrl(queryWord, 30); /for (int i = 1; i <= page; i++) {pageUrl.setPn(i * 30);getJson(pageUrl.toString());}}public String getJson(String url) {String json = null;try (CloseableHttpClient httpClient = HttpClients.createDefault()) {HttpGet getMethod = new HttpGet(url);setHeaders(getMethod);try (CloseableHttpResponse response = httpClient.execute(getMethod)) {int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {HttpEntity entity = response.getEntity();if (entity != null) {json = EntityUtils.toString(entity, "UTF-8");resolveJson(json);}} else {throw new IOException("请求失败:" + statusCode);}}} catch (IOException e) {e.printStackTrace();}return json;}public List<String> resolveJson(String json) {// 使用正则表达式,进行匹配,获取 objURLString regx = "\"thumbURL\":\"(.*?)\",";Pattern p = Pattern.compile(regx);Matcher m = p.matcher(json);List<String> strs = new LinkedList<>();while (m.find()) {strs.add(m.group(0));}// 使用 Stream API 进行处理并返回。return strs.stream().map(s -> s.substring(12, s.length() - 2)).collect(Collectors.toList());}public void download(List<String> urlList) {// 用于统计一些数据AtomicInteger successCount = new AtomicInteger(0), failCount = new AtomicInteger(0),exceptionCount = new AtomicInteger(0);// 设置超时时间RequestConfig config = RequestConfig.custom().setSocketTimeout(10 * 1000).setConnectTimeout(10 * 1000).setConnectionRequestTimeout(10 * 1000).setRedirectsEnabled(false) // 不允许自动重定向,否则会把html页面当成图片下载下来.build();try (CloseableHttpClient httpClient = HttpClients.createDefault()) {urlList.forEach(url -> {HttpGet getMethod = new HttpGet(url);try (CloseableHttpResponse response = httpClient.execute(getMethod)) {int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {HttpEntity entity = response.getEntity();if (entity != null) {String filename = this.getFileName(url);File file = new File("F:/baiduImage/" + filename);if (!file.exists()) {file.getParentFile().mkdirs();}try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {entity.writeTo(out);successCount.getAndIncrement();System.out.println(statusCode + " success: " + url + "\n" + filename);}}} else {failCount.getAndIncrement();System.out.println(statusCode + " fail: " + url);}} catch (IOException e) {e.printStackTrace();exceptionCount.getAndIncrement();System.out.println("IOException: " + url);}});} catch (IOException e1) {e1.printStackTrace();}System.out.println("statistic data[ " + "Success: " + successCount.get() + "\n" + "Fail: " + failCount.get()+ "\n" + "Exception: " + exceptionCount.get() + " ]");}private String getFileName(String url) {String suffix = url.substring(url.lastIndexOf("/") + 1);if (suffix.contains("?")) {suffix = suffix.split("[?]")[0]; // 这个 ? ,不能直接使用,必须转义一下}// 后缀默认就是 jpegsuffix = -1 != suffix.lastIndexOf(".") ? suffix.substring(suffix.lastIndexOf(".")) : ".jpeg";return UUID.randomUUID().toString() + suffix;}public static void setHeaders(HttpGet get) {get.setHeader("Accept",               "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");get.setHeader("Accept-Encoding", "gzip, deflate, br");get.setHeader("Cache-Control", "max-age=0");get.setHeader("Connection", "keep-alive");get.setHeader("Cookie","自己登录的cookie信息");// **自己登录的cookie信息**get.setHeader("Host", "image.baidu.com");get.setHeader("Upgrade-Insecure-Requests", "1");get.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36");}
}

编写main方法获取图片

public static void main(String[] args) throws Exception {PicSpider spider = new PicSpider();List<String> urls=spider.crawlePicture( "高清美景", 5);download(urls);}

跑起来在F:/baiduImage/文件夹可以找到下载的图片;
仅供学习使用

java批量获取百度图片相关推荐

  1. Python实用案例,Python脚本,Python实现批量下载百度图片

    往期回顾 Python实现自动监测Github项目并打开网页 Python实现文件自动归类 Python实现帮你选择双色球号码 Python实现每日更换"必应图片"为"桌 ...

  2. 用Python3批量获取街景图片

    用Python3批量获取百度街景图片 首先去百度官网上申请一个AK. 另外,Python中一些库的配置需要自己去搜索一下,时隔太长,已经不记得自己找的哪些博客了. 话不多说,直接上代码. # _*_ ...

  3. python爬虫实现批量下载百度图片

    今天和小伙伴们合作一个小项目,需要用到景点图片作为数据源,在百度上搜索了一些图片,感觉一个一个手动保存太过麻烦,于是想到用爬虫来下载图片. 本次代码用到了下列一些python模块,需要预先安装Beau ...

  4. python爬虫实战:批量获取VCG图片

    文章目录 前言 一.说明 二.获取网页路径 三.获取图片下载URL 四.批量下载图片 五.完整代码 六.效果展示 前言 当前对版权保护日益严格,因此在此说明获取的图像仅做研究和个人学习使用,禁止用作商 ...

  5. urllib3批量下载百度图片

    ''' urllib3批量下载百度图片 ''' import urllib3 import re start_url = 'http://image.baidu.com/search/index?tn ...

  6. 通过Java批量导出带有图片的Excel文件数据

    批量导出带有图片的Excel文件 一.思路解析 二.关键源码 三.总结 Java通过POI或者一些常见的Excel工具类能够轻易导出后台的结构化数据,但是最近面临一个新需求,需要将对应记录数据和图片网 ...

  7. Java爬取百度图片人脸识别下载高颜值小姐姐图片

    前言: 最近想下载一些比较好看的妹子图片,但又不想去网上一张张的看,于是就想通过爬取图片进行人脸识别下载. 1.首先:在爬取图片时,通过Java请求时会遇到百度安全认证机制,在这里可以模拟浏览器的请求 ...

  8. 用python批量下载网络图片大全_实战干货:用 Python 批量下载百度图片!

    为了做一个图像分类的小项目,需要制作自己的数据集.要想制作数据集,就得从网上下载大量的图片,再统一处理. 这时,一张张的保存下载,就显得很繁琐.那么,有没有一种方法可以把搜索到的图片直接下载到本地电脑 ...

  9. node 批量下载百度图片壁纸

    分析百度图片请求的参数 https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&word="+keyWo ...

最新文章

  1. LeetCode Insert Delete GetRandom O(1) - Duplicates allowed
  2. 065_const关键字
  3. Python字符串练习题
  4. [论文阅读] (06) 万字详解什么是生成对抗网络GAN?经典论文及案例普及
  5. 300本计算机编程的经典书籍下载
  6. 什么是CMMI认证?
  7. UE4实时渲染——渲染前和遮挡
  8. 进程上下文切换 – 残酷的性能杀手(上)
  9. python实现搜索功能_python实现百度识图搜索功能
  10. 【食品加工技术】第四章 饮料生产技术 笔记
  11. Peekaboo(2019年上海网络赛K题+圆上整点)
  12. 13 MCMC(Markov Chain Monte Carlo)
  13. 9-vulnhub靶机-Tr0ll-ssh-rsa-private-环境变量-缓冲区溢出提权
  14. 2017全球智慧城市战略指数分析
  15. 吉利车机安装第三方软件教程,手机修改dns完整操作教程
  16. jdbc批量插入的4种方式【百万条数据插入只需几秒】
  17. windows共享文件创建----局域网办公
  18. 您使用的私钥格式错误,请检查RSA私钥配置,charset = utf-8
  19. Android应用开发-小巫CSDN博客客户端UI篇
  20. PVE安装 virtio

热门文章

  1. JS贪心算法,含图解
  2. 《浪潮之巅》13 幕后的英雄--风险投资
  3. 1.5 x86带宽计算
  4. 微视抄袭抖音?马化腾怒怼张一鸣:诽谤
  5. 视频编码运动估计之全搜索算法(穷尽搜索算法)
  6. 百度新闻首页和百度站长平台首页相继改版
  7. MyZip--专业mac压缩软件
  8. UPnP 体系架构和基本原理 —— Linux SDK for UPnP Devices
  9. Android修行手册 - RatingBar全解
  10. js将身份证号转换为生日和性别