歡迎您的來訪!有源碼,好建站(m.bmm520.net)源碼海洋源碼網為您提供快速建站平臺.
      當前位置: 首頁 > 行業資訊 > java資料 >

      Java爬蟲實戰代碼

      時間:2019-01-25 20:43來源:未知 作者:源碼海洋 點擊:
      Java爬蟲實戰代碼 業務背景 大家在平時的生活或工作種多少都會遇到類似下面的情況吧 非技術人員: 我身邊有同學在一家裝修設計公司上班,她每天的工作就是去其他各大裝修平臺,去借鑒別人家設計師的創意,找到合適的圖片,就會一張張點擊圖片另存到自己電腦

       

      Java爬蟲實戰代碼

       

      業務背景

      大家在平時的生活或工作種多少都會遇到類似下面的情況吧

      非技術人員:

      我身邊有同學在一家裝修設計公司上班,她每天的工作就是去其他各大裝修平臺,去“借鑒”別人家設計師的創意,找到合適的圖片,就會一張張點擊圖片另存到自己電腦中。

      其實這些工作都是重復性且毫無技術含量,完全可以用工具自動化實現。

      技術人員:

      比如我喜歡看一些技術帖子(微信公總號,技術博客等),有時候會覺得文章中的一些技術原理、架構圖片非常直觀,為了方便下次鞏固這些技術,我一般都會把圖片保存下來。

      如果圖片不多的話,一般有如下方法

      1 點擊圖片另存為 (原圖像素還不錯) 
      2 用手機拍照(像素不好)

      如果要下載保存的圖片過多,通過以上兩種方式去抓取圖片,有兩個弊端

      1 效率低下 
      2 重復工作,浪費不必要的時間

      作為一位懶惰的碼農,怎么可以把時間浪費在不需要腦力的事情上呢? 為了減少重復性的工作,便有了這篇文章,我這里寫的并不是很深入,只是提供一個思路,實現簡單從網頁中抓取所有圖片并重命名保存到電腦中;希望對大家有所幫助。

      開發環境

      • jdk1.6&以上
      • Eclipse或Intellij idea
      • Maven

      編碼

      package com.xyq.maventest.util;  import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; 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.lang.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils;   /**** *  * @ClassName: DownloadImageUtil  * @Description: 此類主要作用從一個網址上爬圖片,然后重命名保存到本地路徑中 * @author youqiang.xiong * @date 2018年2月26日 下午12:09:29  * */ public class DownloadImageUtil {      /***      * 請求的網址url常量      */     public static final String REQUEST_URL = "https://www.cnblogs.com/EasonJim/p/6919369.html";     /****      * 圖片保存路徑      */     public static final String IMAGE_SAVE_PATH = "C:\\Users\\youqiang.xiong\\Desktop\\image\\test";      /***      *  獲取img標簽正則表達式      */     public static final String IMGURL_REG = "<img.*src=(.*?)[^>]*?>";       /****      * 獲取src路徑的正則        */     public static final String IMGSRC_REG = "(http|https):\"?(.*?)(\"|>|\\s+)";        public static String[] IMAGE_TYPE_SUFFIX = new String[]{"=png","=jpg","=jpeg",".png",".jpg","jpeg"};     /****      * 生成圖片的名稱默認從1開始遞增      */     public static Integer imageIndex = 1;       public static void main(String[] args) {          //第一步通過請求url解析出響應內容         String htmlContent = parseContext(REQUEST_URL);         //通過正則表達式匹配,取出data-src的圖片鏈接存放到list數組中         //<img class="" data-ratio="0.5993031358885017" data-src="https://mmbiz.qpic.cn/mmbiz_png/dkwuWwLoRK8POMmicDvKwHwYrqrG7KyiaCGBdaib7rOlRlCSfLqaecaXeJvyRGwZZyvmvL9YGiaicNlLs6jlLKaia1icA/640?wx_fmt=png" data-type="png" data-w="861" height="516" style="margin: auto;max-width: 80%;box-sizing: inherit;-webkit-tap-highlight-color: transparent;border-width: initial;border-style: none;border-color: initial;" width="861"  />         List<String> imageUrlList = getImageSrc(htmlContent);          for(String imageUrl:imageUrlList){             try {                 download(imageUrl, IMAGE_SAVE_PATH);             } catch (Exception e) {                 System.out.println(e.getMessage());             }         }          System.out.println("從【"+REQUEST_URL+"】網站,共抓取【"+(imageIndex-1)+"】張圖片。");     }        /***      * 解析圖片url路徑,保存到對應目錄下      * @param oldUrl 圖片鏈接url      * @param savePath 圖片報錯路徑      * @throws Exception      */     public static void download(String oldUrl,String savePath) throws Exception {          String imageType = "";         boolean flag = false;         for(String suffix:IMAGE_TYPE_SUFFIX){             if(oldUrl.lastIndexOf(suffix) > -1 || oldUrl.lastIndexOf(suffix.toUpperCase()) > -1){                 flag = true;                 imageType = suffix.replace("=", ".");                 break;             }         }         //圖片類型存在         if(flag){             String filename = String.valueOf(imageIndex) + imageType;             download(oldUrl, filename, savePath);             imageIndex ++ ;         }     }      /*****      * 根據圖片url路徑,下載到對應目錄下      * @param urlString 圖片url路徑      * @param filename  文件名稱      * @param savePath  文件報錯路徑      * @throws Exception      */     public static void download(String urlString, String filename, String savePath) throws Exception {          if(StringUtils.isEmpty(urlString) || StringUtils.isEmpty(filename) || StringUtils.isEmpty(savePath)){             throw new IllegalArgumentException("方法入參不能為空!");         }         //目錄如果不存在,則新增         File dir = new File(savePath);         if(!dir.exists() && dir.isDirectory()){             dir.mkdirs();         }         // 構造URL         URL url = new URL(urlString);         // 打開連接         URLConnection con = url.openConnection();         // 設置請求超時為5s         con.setConnectTimeout(5 * 1000);         // 輸入流         InputStream is = con.getInputStream();          // 1K的數據緩沖         byte[] bs = new byte[1024];         // 讀取到的數據長度         int len;         // 輸出的文件流         File sf = new File(savePath);         if (!sf.exists()) {             sf.mkdirs();         }         OutputStream os = new FileOutputStream(sf.getPath() + "/" + filename);         // 開始讀取         while ((len = is.read(bs)) != -1) {             os.write(bs, 0, len);         }         // 完畢,關閉所有鏈接         os.close();         is.close();     }        /****      * 通過httpclient,讀取url中的響應內容并返回       * @param url 請求的url路徑      * @return       */     public static String  parseContext(String url) {          if(StringUtils.isEmpty(url)){             throw new IllegalArgumentException("訪問地址url不能為空");         }          String html = null;         // 創建httpclient對象         CloseableHttpClient httpclient = HttpClients.createDefault();         try {             // 創建httpget對象             HttpGet httpGet = new HttpGet(url);             // 執行get請求.             CloseableHttpResponse response = httpclient.execute(httpGet);             try {                 // 獲取響應實體                 HttpEntity entity = response.getEntity();                 if (entity != null) {                     html = EntityUtils.toString(entity);                 }             } finally {                 response.close();             }         } catch (ClientProtocolException e) {             e.printStackTrace();         } catch (ParseException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         } finally {             // 關閉連接,釋放資源             try {                 httpclient.close();             } catch (IOException e) {                 e.printStackTrace();             }         }          return html;     }        /***       * 獲取ImageUrl地址       *        * @param htmlContext       * @return       */       private static List<String> getImageUrl(String htmlContext) {            if(StringUtils.isEmpty(htmlContext)){             throw new IllegalArgumentException("html請求內容不能為空.");         }          List<String> listImgUrl = new ArrayList<String>();            Matcher matcher = Pattern.compile(IMGURL_REG).matcher(htmlContext);            while (matcher.find()) {               listImgUrl.add(matcher.group().replaceAll("'", ""));           }            return listImgUrl;       }        /***       * 獲取ImageSrc地址       *        * @param htmlContext       * @return       */       public static  List<String> getImageSrc(String htmlContext) {            if(StringUtils.isEmpty(htmlContext)){             throw new IllegalArgumentException("html請求內容不能為空.");         }         List<String> listImageUrl = getImageUrl(htmlContext);          List<String> listImgSrc = new ArrayList<String>();            for (String imageContext : listImageUrl) {               Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(imageContext);               while (matcher.find()) {                   listImgSrc.add(matcher.group().substring(0, matcher.group().length() - 1));               }           }           return listImgSrc;       }    } 
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
      • 57
      • 58
      • 59
      • 60
      • 61
      • 62
      • 63
      • 64
      • 65
      • 66
      • 67
      • 68
      • 69
      • 70
      • 71
      • 72
      • 73
      • 74
      • 75
      • 76
      • 77
      • 78
      • 79
      • 80
      • 81
      • 82
      • 83
      • 84
      • 85
      • 86
      • 87
      • 88
      • 89
      • 90
      • 91
      • 92
      • 93
      • 94
      • 95
      • 96
      • 97
      • 98
      • 99
      • 100
      • 101
      • 102
      • 103
      • 104
      • 105
      • 106
      • 107
      • 108
      • 109
      • 110
      • 111
      • 112
      • 113
      • 114
      • 115
      • 116
      • 117
      • 118
      • 119
      • 120
      • 121
      • 122
      • 123
      • 124
      • 125
      • 126
      • 127
      • 128
      • 129
      • 130
      • 131
      • 132
      • 133
      • 134
      • 135
      • 136
      • 137
      • 138
      • 139
      • 140
      • 141
      • 142
      • 143
      • 144
      • 145
      • 146
      • 147
      • 148
      • 149
      • 150
      • 151
      • 152
      • 153
      • 154
      • 155
      • 156
      • 157
      • 158
      • 159
      • 160
      • 161
      • 162
      • 163
      • 164
      • 165
      • 166
      • 167
      • 168
      • 169
      • 170
      • 171
      • 172
      • 173
      • 174
      • 175
      • 176
      • 177
      • 178
      • 179
      • 180
      • 181
      • 182
      • 183
      • 184
      • 185
      • 186
      • 187
      • 188
      • 189
      • 190
      • 191
      • 192
      • 193
      • 194
      • 195
      • 196
      • 197
      • 198
      • 199
      • 200
      • 201
      • 202
      • 203
      • 204
      • 205
      • 206
      • 207
      • 208
      • 209
      • 210
      • 211
      • 212
      • 213
      • 214
      • 215
      • 216
      • 217
      • 218
      • 219
      • 220
      • 221
      • 222
      • 223
      • 224
      • 225
      • 226
      • 227
      • 228
      • 229
      • 230
      • 231
      • 232
      • 233
      • 234
      • 235
      • 236
      • 237
      • 238
      • 239
      • 240
      • 241
      • 242
      • 243
      • 244
      • 245
      • 246
      • 247
      • 248
      • 249
      • 250
      • 251

      說明需要引入httpclient和commons-lang兩個jar包

      我的項目是通過maven管理,所以只需要在pom.xml中添加以下配置即可

              <!-- apache開源組織的jar包 -->         <dependency>             <groupId>org.apache.httpcomponents</groupId>             <artifactId>httpclient</artifactId>             <version>4.5.4</version>         </dependency>         <!-- apache提供的工具jar,包含 字符串,數字、反射等工具類-->         <dependency>             <groupId>commons-lang</groupId>             <artifactId>commons-lang</artifactId>             <version>2.6</version>           </dependency>
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12

      測試效果

      1、修改常量

      修改RQQUEST_URL 和IMAGE_SAVE_PATH 兩個常量值改成你想抓取的網址url和保存圖片的路徑即可

           /***      * 請求的網址url常量      */ public static final String RQQUEST_URL = "https://www.cnblogs.com/EasonJim/p/6919369.html";     /****      * 圖片保存路徑      */ public static final String IMAGE_SAVE_PATH = "C:\\Users\\youqiang.xiong\\Desktop\\image\\test";
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8

      2、運行main方法

      3、等待不久,Console控制臺會輸出一段信息

      從【https://www.cnblogs.com/EasonJim/p/6919369.html】網站,共抓取【7】張圖片。
      • 1

      這里寫圖片描述

      4、打開C:\Users\youqiang.xiong\Desktop\image\test 目錄查看圖片是否成功生成

      這里寫圖片描述

      對比https://www.cnblogs.com/EasonJim/p/6919369.html 網址上的圖片跟test目錄中的發現一模一樣,這樣就大功告成了。

      TODO

      以上功能還有一些需要完善和優化的地方,由于時間有限這里還沒有太多時間去研究,后續會進一步補充。

      1 加入多線程,同時抓取多個網站的圖片 
      2 利用Java swing技術開發圖形界面,供普通用戶使用

       

      (責任編輯:源碼海洋)本文地址:http://m.bmm520.net/info/java/2019/0125/17175.html

      推薦資訊

      亚洲中文字幕无码爆乳av中文| 亚洲精品国产精品国自产网站 | 亚洲乱亚洲乱妇24p| 久久久久亚洲爆乳少妇无| 国产亚洲精品不卡在线| 亚洲国产精品xo在线观看| 亚洲欧美国产欧美色欲| 亚洲女人影院想要爱| 亚洲精品白色在线发布| 国产亚洲AV夜间福利香蕉149| 亚洲国产精品人人做人人爱| 亚洲日韩精品国产3区| 亚洲熟妇丰满xxxxx| 伊在人亚洲香蕉精品区麻豆| 亚洲高清在线观看| 亚洲人成综合网站7777香蕉| 激情综合亚洲色婷婷五月APP| 中文字幕第一页亚洲| 国产国拍亚洲精品福利| 国产亚洲人成在线播放| 亚洲欧洲高清有无| 亚洲毛片在线观看| 久久精品亚洲综合专区| 亚洲高清视频在线播放| 亚洲av日韩av欧v在线天堂| 亚洲乱亚洲乱妇无码麻豆| 亚洲H在线播放在线观看H| 国产成人高清亚洲一区久久| 亚洲日韩中文字幕无码一区| 亚洲日本人成中文字幕| 亚洲人妖女同在线播放| 亚洲一级毛片免费观看| 亚洲人成伊人成综合网久久| 亚洲天堂电影在线观看| 色偷偷女男人的天堂亚洲网| 亚洲国产精品专区| ass亚洲**毛茸茸pics| 亚洲 日韩经典 中文字幕| 亚洲fuli在线观看| 亚洲av成人一区二区三区| 亚洲日本在线电影|