jsoup爬取百度瀑布流图片

是的,Java也可以做网络爬虫,不仅可以爬静态网页的图片,也可以爬动态网页的图片,比如采用Ajax技术进行异步加载的百度瀑布流。

以前有写过用Java进行百度图片的抓取,但只能抓取到第一二页,本博文则对此问题进行了深入研究,提出了另外一种思路解决问题。我的思路是这样的:以前人们总认为既然百度瀑布流是采用JavaScript进行异步加载的,那么爬取图片至少要有一个模拟浏览器,比如Java领域中的无界面浏览器工具HtmlUnit,但后来我发现其实Jsoup也是可以的,只要用Jsoup去向百度服务器发送Ajax请求就行了,幸运的是我在观察百度图片的ajax请求时还真发现有两个类型的请求方式:avatarjson和acjson,实验告诉我们第一种请求方式已经几乎可以满足我们的所有需求。

本博文所实现的效果是:根据输入的多个关键字,可以按定制的页数把各自关键字的搜索结果下载到本地文件夹中。具体如下所示:

废话不多说,程序满上------->

  1. package com.kendy.spider;
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. import java.net.URLConnection;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.util.regex.Matcher;
  13. import java.util.regex.Pattern;
  14. import org.apache.commons.lang3.StringEscapeUtils;
  15. import org.jsoup.Jsoup;
  16. import org.jsoup.nodes.Document;
  17. // 爬取百度图片
  18. public class JsoupBaidu2 {
  19. public static void main(String[] args) throws Exception{
  20. String downloadPath = "C:\\Users\\Kendy\\Desktop\\中国明星图";
  21. List<String> list = nameList("凯莉·布鲁克 詹妮弗·洛佩兹 碧昂斯·诺里斯");
  22. getPictures(list,1,downloadPath); //1代表下载一页,一页一般有30张图片
  23. }
  24. public static void getPictures(List<String> keywordList, int max,String downloadPath) throws Exception{ // key为关键词,max作为爬取的页数
  25. String gsm=Integer.toHexString(max)+"";
  26. String finalURL = "";
  27. String tempPath = "";
  28. for(String keyword : keywordList){
  29. tempPath = downloadPath;
  30. if(!tempPath.endsWith("\\")){
  31. tempPath = downloadPath+"\\";
  32. }
  33. tempPath = tempPath+keyword+"\\";
  34. File f = new File(tempPath);
  35. if(!f.exists()){
  36. f.mkdirs();
  37. }
  38. int picCount = 1;
  39. for(int page=0;page<=max;page++) {
  40. sop("正在下载第"+page+"页面");
  41. Document document = null;
  42. try {
  43. 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);
  44. sop(url);
  45. document = Jsoup.connect(url).data("query", "Java")//请求参数
  46. .userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)")//设置urer-agent  get();
  47. .timeout(5000)
  48. .get();
  49. String xmlSource = document.toString();
  50. xmlSource = StringEscapeUtils.unescapeHtml3(xmlSource);
  51. sop(xmlSource);
  52. String reg = "objURL\":\"http://.+?\\.jpg";
  53. Pattern pattern = Pattern.compile(reg);
  54. Matcher m = pattern.matcher(xmlSource);
  55. while (m.find()) {
  56. finalURL = m.group().substring(9);
  57. sop(keyword+picCount+++":"+finalURL);
  58. download(finalURL,tempPath);
  59. sop("             下载成功");
  60. }
  61. } catch (IOException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. }
  66. sop("下载完毕");
  67. delMultyFile(downloadPath);
  68. sop("已经删除所有空图");
  69. }
  70. public static void delMultyFile(String path){
  71. File file = new File(path);
  72. if(!file.exists())
  73. throw new RuntimeException("File \""+path+"\" NotFound when excute the method of delMultyFile()....");
  74. File[] fileList = file.listFiles();
  75. File tempFile=null;
  76. for(File f : fileList){
  77. if(f.isDirectory()){
  78. delMultyFile(f.getAbsolutePath());
  79. }else{
  80. if(f.length()==0)
  81. sop(f.delete()+"---"+f.getName());
  82. }
  83. }
  84. }
  85. public static List<String> nameList(String nameList){
  86. List<String> arr = new ArrayList<>();
  87. String[] list;
  88. if(nameList.contains(","))
  89. list= nameList.split(",");
  90. else if(nameList.contains("、"))
  91. list= nameList.split("、");
  92. else if(nameList.contains(" "))
  93. list= nameList.split(" ");
  94. else{
  95. arr.add(nameList);
  96. return arr;
  97. }
  98. for(String s : list){
  99. arr.add(s);
  100. }
  101. return arr;
  102. }
  103. public static void sop(Object obj){
  104. System.out.println(obj);
  105. }
  106. //根据图片网络地址下载图片
  107. public static void download(String url,String path){
  108. //path = path.substring(0,path.length()-2);
  109. File file= null;
  110. File dirFile=null;
  111. FileOutputStream fos=null;
  112. HttpURLConnection httpCon = null;
  113. URLConnection  con = null;
  114. URL urlObj=null;
  115. InputStream in =null;
  116. byte[] size = new byte[1024];
  117. int num=0;
  118. try {
  119. String downloadName= url.substring(url.lastIndexOf("/")+1);
  120. dirFile = new File(path);
  121. if(!dirFile.exists() && path.length()>0){
  122. if(dirFile.mkdir()){
  123. sop("creat document file \""+path.substring(0,path.length()-1)+"\" success...\n");
  124. }
  125. }else{
  126. file = new File(path+downloadName);
  127. fos = new FileOutputStream(file);
  128. if(url.startsWith("http")){
  129. urlObj = new URL(url);
  130. con = urlObj.openConnection();
  131. httpCon =(HttpURLConnection) con;
  132. in = httpCon.getInputStream();
  133. while((num=in.read(size)) != -1){
  134. for(int i=0;i<num;i++)
  135. fos.write(size[i]);
  136. }
  137. }
  138. }
  139. }catch (FileNotFoundException notFoundE) {
  140. sop("找不到该网络图片....");
  141. }catch(NullPointerException nullPointerE){
  142. sop("找不到该网络图片....");
  143. }catch(IOException ioE){
  144. sop("产生IO异常.....");
  145. }catch (Exception e) {
  146. e.printStackTrace();
  147. }finally{
  148. try {
  149. fos.close();
  150. } catch (Exception e) {
  151. e.printStackTrace();
  152. }
  153. }
  154. }
  155. }

Java jsoup爬取图片的更多相关文章

  1. jsoup爬取图片到本地

    因为项目需求,需要车辆品牌信息和车系信息,昨天用一天时间研究了jsoup爬取网站信息.项目是用maven+spring+springmvc+mybatis写的. jsoup开发指南地址:http:// ...

  2. java 利用jsoup 爬取知乎首页问题

    今天学了下java的爬虫,首先要下载jsoup的包,然后导入,导入过程:首先右击工程:Build Path ->configure Build Path,再点击Add External JARS ...

  3. Jsoup爬取带登录验证码的网站

    今天学完爬虫之后想的爬一下我们学校的教务系统,可是发现登录的时候有验证码.因此研究了Jsoup爬取带验证码的网站: 大体的思路是:(需要注意的是__VIEWSTATE一直变化,所以我们每个页面都需要重 ...

  4. [python爬虫] 爬取图片无法打开或已损坏的简单探讨

    本文主要针对python使用urlretrieve或urlopen下载百度.搜狗.googto(谷歌镜像)等图片时,出现"无法打开图片或已损坏"的问题,作者对它进行简单的探讨.同时 ...

  5. jsoup爬取某网站安全数据

    jsoup爬取某网站安全数据 package com.vfsd.net; import java.io.IOException; import java.sql.SQLException; impor ...

  6. Java实现爬取京东手机数据

    Java实现爬取京东手机数据 最近看了某马的Java爬虫视频,看完后自己上手操作了下,基本达到了爬数据的要求,HTML页面源码也刚好复习了下,之前发布两篇关于简单爬虫的文章,也刚好用得上.项目没什么太 ...

  7. [java] jsoup使用简介-汇率换算器实现-插曲2

    [java] jsoup使用简介-汇率换算器实现-插曲2 // */ // ]]>   [java] jsoup使用简介-汇率换算器实现-插曲2 Table of Contents 1 系列文章 ...

  8. python如何使用request爬取图片

    下面是代码的简单实现,变量名和方法都是跑起来就行,没有整理,有需要的可以自己整理下: image2local: import requests import time from lxml import ...

  9. 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  ...

随机推荐

  1. Spring Data JPA 入门Demo

    什么是JPA呢? 其实JPA可以说是一种规范,是java5.0之后提出来的用于持久化的一套规范:它不是任何一种ORM框架,在我看来,是现有ORM框架在这个规范下去实现持久层. 它的出现是为了简化现有的 ...

  2. Redis--配置密码

    可以通过以下方法进行密码的配置: ① 修改配置文件设置密码 ② 通过命令修改密码(重启redis后,新设置的密码会失效) 此处介绍第一种 1. 找到redis的配置文件,一般在/etc/redis.c ...

  3. eclipse Maven配置

    ①下载:http://maven.apache.org/download.cgi ②解压至:F:\Study\apache-maven-3.5.2 ③配置环境变量 变量名:M2_HOME 变量值:F: ...

  4. 【前端】Vue2全家桶案例《看漫画》之一、添加四个导航页

    转载请注明出处:http://www.cnblogs.com/shamoyuu/p/vue_vux_app_1.html 项目github地址:https://github.com/shamoyuu/ ...

  5. AutoAudit研究学习

    AutoAudit介绍   AutoAudit这个是Paul Nielsen写的一个开源的审计跟踪的脚本项目,项目位于https://autoaudit.codeplex.com/上,Paul Nie ...

  6. 对HI3531的GPIO使用的再分析

    在一个嵌入式系统中使用最多的莫过于 通用输入输出 GPIO口.看到论坛中经常有朋友问海思为什么没有提供GPIO驱动.其实不然. 在海思SDK  xxx/osdrv/tools/board_tools/ ...

  7. PCI9054 学习小结

    PCI的基本协议这里就不介绍了,因为一般的芯片协议都是集成好的,我只需要大体了解就行,不需要做芯片,我感觉就不需要太了解协议. 这里讲解是基于PLX 的9054(9052)芯片为基础的,本人只是入门, ...

  8. 如何给filter添加自定义接口

    .在Cfilter类的定义中实现Interface接口的函数的定义: //-----------------------Interface methods----------------------- ...

  9. gplots heatmap.2和ggplot2 geom_tile实现数据聚类和热图plot

    主要步骤 ggplot2 数据处理成矩阵形式,给行名列名 hclust聚类,改变矩阵行列顺序为聚类后的顺序 melt数据,处理成ggplot2能够直接处理的数据结构,并加上列名 ggplot_tile ...

  10. 觉得OpenStack的网络复杂?其实你家里就有同样一个网络

    当你想了解OpenStack的Neutron网络,打开下面这张图的时候,心里一定是崩溃的,看起来这些模块连在一起很复杂,但其实和你家里的网络很像,看不出来?看我来慢慢解析. 其实这个网络的样子更像是我 ...