zoukankan      html  css  js  c++  java
  • Java jsoup爬取图片

    jsoup爬取百度瀑布流图片

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

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

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

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

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. package com.kendy.spider;  
    2.   
    3. import java.io.File;  
    4. import java.io.FileNotFoundException;  
    5. import java.io.FileOutputStream;  
    6. import java.io.IOException;  
    7. import java.io.InputStream;  
    8. import java.net.HttpURLConnection;  
    9. import java.net.URL;  
    10. import java.net.URLConnection;  
    11. import java.util.ArrayList;  
    12. import java.util.List;  
    13. import java.util.regex.Matcher;  
    14. import java.util.regex.Pattern;  
    15.   
    16. import org.apache.commons.lang3.StringEscapeUtils;  
    17. import org.jsoup.Jsoup;  
    18. import org.jsoup.nodes.Document;  
    19.   
    20. // 爬取百度图片  
    21. public class JsoupBaidu2 {  
    22.       
    23.     public static void main(String[] args) throws Exception{  
    24.         String downloadPath = "C:\Users\Kendy\Desktop\中国明星图";  
    25.         List<String> list = nameList("凯莉·布鲁克 詹妮弗·洛佩兹 碧昂斯·诺里斯");  
    26.         getPictures(list,1,downloadPath); //1代表下载一页,一页一般有30张图片  
    27.     }  
    28.       
    29.     public static void getPictures(List<String> keywordList, int max,String downloadPath) throws Exception{ // key为关键词,max作为爬取的页数  
    30.         String gsm=Integer.toHexString(max)+"";  
    31.         String finalURL = "";  
    32.         String tempPath = "";  
    33.        for(String keyword : keywordList){  
    34.            tempPath = downloadPath;  
    35.            if(!tempPath.endsWith("\")){  
    36.             tempPath = downloadPath+"\";  
    37.            }  
    38.            tempPath = tempPath+keyword+"\";  
    39.            File f = new File(tempPath);  
    40.            if(!f.exists()){  
    41.                f.mkdirs();  
    42.            }  
    43.            int picCount = 1;  
    44.            for(int page=0;page<=max;page++) {   
    45.                sop("正在下载第"+page+"页面");  
    46.                 Document document = null;  
    47.                 try {  
    48.                     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);  
    49.                     sop(url);  
    50.                     document = Jsoup.connect(url).data("query", "Java")//请求参数    
    51.                              .userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)")//设置urer-agent  get();  
    52.                              .timeout(5000)  
    53.                              .get();  
    54.                     String xmlSource = document.toString();  
    55.                     xmlSource = StringEscapeUtils.unescapeHtml3(xmlSource);  
    56.                     sop(xmlSource);  
    57.                     String reg = "objURL":"http://.+?\.jpg";  
    58.                     Pattern pattern = Pattern.compile(reg);  
    59.                     Matcher m = pattern.matcher(xmlSource);  
    60.                     while (m.find()) {  
    61.                         finalURL = m.group().substring(9);  
    62.                         sop(keyword+picCount+++":"+finalURL);  
    63.                         download(finalURL,tempPath);  
    64.                         sop("             下载成功");  
    65.                     }   
    66.                 } catch (IOException e) {  
    67.                     e.printStackTrace();  
    68.                 }  
    69.             }  
    70.        }  
    71.        sop("下载完毕");  
    72.        delMultyFile(downloadPath);  
    73.        sop("已经删除所有空图");  
    74.     }  
    75.     public static void delMultyFile(String path){  
    76.         File file = new File(path);  
    77.         if(!file.exists())  
    78.             throw new RuntimeException("File ""+path+"" NotFound when excute the method of delMultyFile()....");  
    79.         File[] fileList = file.listFiles();  
    80.         File tempFile=null;  
    81.         for(File f : fileList){  
    82.             if(f.isDirectory()){  
    83.                 delMultyFile(f.getAbsolutePath());  
    84.             }else{  
    85.                 if(f.length()==0)  
    86.                     sop(f.delete()+"---"+f.getName());  
    87.             }  
    88.         }  
    89.     }  
    90.     public static List<String> nameList(String nameList){  
    91.         List<String> arr = new ArrayList<>();  
    92.         String[] list;  
    93.         if(nameList.contains(","))  
    94.             list= nameList.split(",");  
    95.         else if(nameList.contains("、"))  
    96.             list= nameList.split("、");  
    97.         else if(nameList.contains(" "))  
    98.             list= nameList.split(" ");  
    99.         else{  
    100.             arr.add(nameList);  
    101.             return arr;  
    102.         }  
    103.         for(String s : list){  
    104.             arr.add(s);  
    105.         }  
    106.         return arr;  
    107.     }  
    108.     public static void sop(Object obj){  
    109.         System.out.println(obj);  
    110.     }  
    111.   //根据图片网络地址下载图片  
    112.     public static void download(String url,String path){  
    113.         //path = path.substring(0,path.length()-2);  
    114.         File file= null;  
    115.         File dirFile=null;  
    116.         FileOutputStream fos=null;  
    117.         HttpURLConnection httpCon = null;  
    118.         URLConnection  con = null;  
    119.         URL urlObj=null;  
    120.         InputStream in =null;  
    121.         byte[] size = new byte[1024];  
    122.         int num=0;  
    123.         try {  
    124.             String downloadName= url.substring(url.lastIndexOf("/")+1);  
    125.             dirFile = new File(path);  
    126.             if(!dirFile.exists() && path.length()>0){  
    127.                 if(dirFile.mkdir()){  
    128.                     sop("creat document file ""+path.substring(0,path.length()-1)+"" success... ");  
    129.                 }  
    130.             }else{  
    131.                 file = new File(path+downloadName);  
    132.                 fos = new FileOutputStream(file);  
    133.                 if(url.startsWith("http")){  
    134.                     urlObj = new URL(url);  
    135.                     con = urlObj.openConnection();  
    136.                     httpCon =(HttpURLConnection) con;  
    137.                     in = httpCon.getInputStream();  
    138.                     while((num=in.read(size)) != -1){  
    139.                         for(int i=0;i<num;i++)  
    140.                            fos.write(size[i]);  
    141.                     }  
    142.                 }  
    143.             }  
    144.         }catch (FileNotFoundException notFoundE) {  
    145.             sop("找不到该网络图片....");  
    146.         }catch(NullPointerException nullPointerE){  
    147.             sop("找不到该网络图片....");  
    148.         }catch(IOException ioE){  
    149.             sop("产生IO异常.....");  
    150.         }catch (Exception e) {  
    151.             e.printStackTrace();  
    152.         }finally{  
    153.             try {  
    154.                 fos.close();  
    155.             } catch (Exception e) {  
    156.                 e.printStackTrace();  
    157.             }  
    158.         }  
    159.     }  
    160. }  
  • 相关阅读:
    常用算法解析-动态规划
    转载-通过ApplicationContext 去获取所有的Bean
    什么是crud?
    new 关键字 和 newInstance() 方法的 区别
    Java反射简单使用--第一次细致阅读底层代码
    动态创建管理定时任务-已完成
    springboot mail整合freemark实现动态生成模板
    20190930开始记录每天学习状态,更新至20200125结束
    hibernate的对象/关系映射结果为空,exists查不到值的问题-20190823
    转载-Java中LinkedList的一些方法—addFirst addFirst getFirst geLast removeFirst removeLast
  • 原文地址:https://www.cnblogs.com/tutu21ybz/p/6738878.html
Copyright © 2011-2022 走看看