Java實現(xiàn)爬取百度圖片的方法分析
本文實例講述了Java實現(xiàn)爬取百度圖片的方法。分享給大家供大家參考,具體如下:
在以往用java來處理解析HTML文檔或者片段時,我們通常會采用htmlparser(http://htmlparser.sourceforge.net/)這個開源類庫。現(xiàn)在我們有了JSOUP,以后的處理HTML的內容只需要使用JSOUP就已經(jīng)足夠了,JSOUP有更快的更新,更方便的API等。
jsoup 是一款 Java 的HTML 解析器,可直接解析某個URL地址、HTML文本內容。它提供了一套非常省力的API,可通過DOM,CSS以及類似于jQuery的操作方法來取出和操作數(shù)據(jù),可以看作是java版的jQuery。
jsoup的主要功能如下:
- 從一個URL,文件或字符串中解析HTML;
- 使用DOM或CSS選擇器來查找、取出數(shù)據(jù);
- 可操作HTML元素、屬性、文本;
jsoup是基于MIT協(xié)議發(fā)布的,可放心使用于商業(yè)項目。官方網(wǎng)站:http://jsoup.org/
步驟大致可以分為三個模塊:一是獲取網(wǎng)頁的資源,二是解析獲取的資源,取出我們想要的圖片URL地址,三是通過java的io存儲在本地文件中。
獲取網(wǎng)頁資源的核心模塊就是通過Jsoup去獲取網(wǎng)頁的內容,具體核心代碼如下:
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)")//設置urer-agent get();
.timeout(timeOut)
.get();
String xmlSource = document.toString();
result = dealResult(xmlSource, hotelId);
} catch (Exception e) {
String defaultURL = "http://qnimg.zowoyoo.com/img/15463/1509533934407.jpg";
result = dealResult(defaultURL,hotelId);
}
return result;
}
其中URL地址是百度圖片搜索的地址,具體調用代碼如下:
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是我們要搜索的關鍵字,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 = "http://qnimg.zowoyoo.com/img/15463/1509533934407.jpg";
jsoupImageVO.setUrl(defaultURL);
}else{
jsoupImageVO.setUrl(imageURL);
}
jsoupImageVO.setName(hotelId);
result.add(jsoupImageVO);
}
return result;
}
這里最主要的地方就是reg這個正則表達式,通過正則表達式,去網(wǎng)頁中解析符合規(guī)定的圖片URL地址,然后封裝在對象中。
最后一部分就是通過java的io流去圖片地址獲取圖片,并保存在本地。核心代碼如下:
//根據(jù)圖片網(wǎng)絡地址下載圖片
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)絡圖片....");
}catch(NullPointerException nullPointerE){
LogUtils.writeLog("找不到該網(wǎng)絡圖片....");
}catch(IOException ioE){
LogUtils.writeLog("產(chǎn)生IO異常.....");
}catch (Exception e) {
e.printStackTrace();
}finally{
try {
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
這里面的操作都是java中io篇一些基礎的操作,有不懂的可以去看看java中io模塊的內容。
因為我這邊是maven項目,所以在開發(fā)前需要引入Jsoup依賴才可以。
源碼可點擊此處本站下載。
更多關于java相關內容感興趣的讀者可查看本站專題:《Java網(wǎng)絡編程技巧總結》、《Java Socket編程技巧總結》、《Java文件與目錄操作技巧匯總》、《Java數(shù)據(jù)結構與算法教程》、《Java操作DOM節(jié)點技巧總結》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章
SpringBoot?快速實現(xiàn)?api?接口加解密功能
在項目中,為了保證數(shù)據(jù)的安全,我們常常會對傳遞的數(shù)據(jù)進行加密,Spring?Boot接口加密,可以對返回值、參數(shù)值通過注解的方式自動加解密,這篇文章主要介紹了SpringBoot?快速實現(xiàn)?api?接口加解密功能,感興趣的朋友一起看看吧2023-10-10
Nacos服務發(fā)現(xiàn)并發(fā)啟動scheduleUpdate定時任務的流程分析
這篇文章主要介紹了Nacos服務發(fā)現(xiàn)并發(fā)啟動scheduleUpdate定時任務,本文結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02
Spring?Boot?3.4.3?基于?Spring?WebFlux?實現(xiàn)?SSE?功能(代碼示例)
Spring Boot 3.4.3 結合Spring WebFlux實現(xiàn)SSE 功能,為實時數(shù)據(jù)推送提供了優(yōu)雅的解決方案,通過本文的步驟,你可以快速搭建一個基于事件驅動的后端服務,滿足實時通知或監(jiān)控等需求,感興趣的朋友一起看看吧2025-04-04

