您好,登錄后才能下訂單哦!
本文實例講述了Java實現(xiàn)爬取百度圖片的方法。分享給大家供大家參考,具體如下:
在以往用java來處理解析HTML文檔或者片段時,我們通常會采用htmlparser(http://htmlparser.sourceforge.net/)這個開源類庫?,F(xiàn)在我們有了JSOUP,以后的處理HTML的內(nèi)容只需要使用JSOUP就已經(jīng)足夠了,JSOUP有更快的更新,更方便的API等。
jsoup 是一款 Java 的HTML 解析器,可直接解析某個URL地址、HTML文本內(nèi)容。它提供了一套非常省力的API,可通過DOM,CSS以及類似于jQuery的操作方法來取出和操作數(shù)據(jù),可以看作是java版的jQuery。
jsoup的主要功能如下:
jsoup是基于MIT協(xié)議發(fā)布的,可放心使用于商業(yè)項目。官方網(wǎng)站:http://jsoup.org/
步驟大致可以分為三個模塊:一是獲取網(wǎng)頁的資源,二是解析獲取的資源,取出我們想要的圖片URL地址,三是通過java的io存儲在本地文件中。
獲取網(wǎng)頁資源的核心模塊就是通過Jsoup去獲取網(wǎng)頁的內(nèi)容,具體核心代碼如下:
private static List<JsoupImageVO> findImageNoURl(String hotelId, String url, int timeOut) { List<JsoupImageVO> result = new ArrayList<JsoupImageVO>(); Document document = null; try { document = Jsoup.connect(url).data("query", "Java")//請求參數(shù) .userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)")//設(shè)置urer-agent get(); .timeout(timeOut) .get(); String xmlSource = document.toString(); result = dealResult(xmlSource, hotelId); } catch (Exception e) { String defaultURL = "https://cache.yisu.com/upload/information/20200623/121/99971.jpg"; result = dealResult(defaultURL,hotelId); } return result; }
其中URL地址是百度圖片搜索的地址,具體調(diào)用代碼如下:
public static List<JsoupImageVO> findImage(String hotelName, String hotelId, int page) { int number=5; String url = "http://image.baidu.com/search/avatarjson?tn=resultjsonavatarnew&ie=utf-8&word=" + hotelName + "&cg=star&pn=" + page * 30 + "&rn="+number+"&itg=0&z=0&fr=&width=&height=&lm=-1&ic=0&s=0&st=-1&gsm=" + Integer.toHexString(page * 30); int timeOut = 5000; return findImageNoURl(hotelId, url, timeOut); }
這里需要注意的是:word是我們要搜索的關(guān)鍵字,pn是顯示的頁碼,rn是一頁顯示多少個數(shù)據(jù)。
解析網(wǎng)頁的資源,然后封裝起來。核心代碼如下:
private static List<JsoupImageVO> dealResult(String xmlSource, String hotelId) { List<JsoupImageVO> result = new ArrayList<JsoupImageVO>(); xmlSource = StringEscapeUtils.unescapeHtml3(xmlSource); String reg = "objURL\":\"http://.+?\\.(gif|jpeg|png|jpg|bmp)"; Pattern pattern = Pattern.compile(reg); Matcher m = pattern.matcher(xmlSource); while (m.find()) { JsoupImageVO jsoupImageVO = new JsoupImageVO(); String imageURL = m.group().substring(9); if(imageURL==null || "".equals(imageURL)){ String defaultURL = "https://cache.yisu.com/upload/information/20200623/121/99971.jpg"; jsoupImageVO.setUrl(defaultURL); }else{ jsoupImageVO.setUrl(imageURL); } jsoupImageVO.setName(hotelId); result.add(jsoupImageVO); } return result; }
這里最主要的地方就是reg這個正則表達(dá)式,通過正則表達(dá)式,去網(wǎng)頁中解析符合規(guī)定的圖片URL地址,然后封裝在對象中。
最后一部分就是通過java的io流去圖片地址獲取圖片,并保存在本地。核心代碼如下:
//根據(jù)圖片網(wǎng)絡(luò)地址下載圖片 public static void download(String url,String name,String path){ 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 { dirFile = new File(path); if(dirFile.exists()){ dirFile.delete(); } dirFile.mkdir(); file = new File(path+"http://"+name+".jpg"); 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) { LogUtils.writeLog("找不到該網(wǎng)絡(luò)圖片...."); }catch(NullPointerException nullPointerE){ LogUtils.writeLog("找不到該網(wǎng)絡(luò)圖片...."); }catch(IOException ioE){ LogUtils.writeLog("產(chǎn)生IO異常....."); }catch (Exception e) { e.printStackTrace(); }finally{ try { fos.close(); } catch (Exception e) { e.printStackTrace(); } } }
這里面的操作都是java中io篇一些基礎(chǔ)的操作,有不懂的可以去看看java中io模塊的內(nèi)容。
因為我這邊是maven項目,所以在開發(fā)前需要引入Jsoup依賴才可以。
源碼可點擊此處本站下載。
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java網(wǎng)絡(luò)編程技巧總結(jié)》、《Java Socket編程技巧總結(jié)》、《Java文件與目錄操作技巧匯總》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。