Java 根據(jù)網(wǎng)絡(luò)URL獲取該網(wǎng)頁上面所有的img標(biāo)簽并下載圖片
說明:根據(jù)網(wǎng)絡(luò)URL獲取該網(wǎng)頁上面所有的img標(biāo)簽并下載符合要求的所有圖片
所需jar包:jsoup.jar
import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import java.util.ArrayList;import java.util.List;import java.util.UUID;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;/** * 圖片批量下載工具類 * @author Marydon * @create time 2016-9-3下午2:01:03 * @update time 2017年9月30日11:07:02 * @E-mail:dellshouji@163.com */public class ImgDownloadUtil { /** * 根據(jù)URL獲取網(wǎng)頁DOM對(duì)象 * @param url * 網(wǎng)址 * @return DOM對(duì)象 */ public static Document getHtmlDocument(String url) { Document document = null; URL urlObj = null; try { // 1.建立網(wǎng)絡(luò)連接 urlObj = new URL(url); // 2.根據(jù)url獲取Document對(duì)象 document = Jsoup.parse(urlObj, 5000);// 單位:毫秒超時(shí)時(shí)間 } catch (MalformedURLException e) { System.out.println('世界上最遙遠(yuǎn)的距離就是沒有網(wǎng),檢查設(shè)置!'); e.printStackTrace(); } catch (IOException e) { System.out.println('您的網(wǎng)絡(luò)連接打開失敗,請(qǐng)稍后重試!'); e.printStackTrace(); } return document; } /** * 根據(jù)URL獲取網(wǎng)頁源碼 * @param url * 網(wǎng)址 * @return 網(wǎng)頁源碼 */ public static String getHtmlText(String url) { String htmlText = ''; Document document = null; URL urlObj = null; try { // 1.建立網(wǎng)絡(luò)連接 urlObj = new URL(url); // 2.根據(jù)url獲取Document對(duì)象 document = Jsoup.parse(urlObj, 5000);// 單位:毫秒超時(shí)時(shí)間 // 3.根據(jù)dom對(duì)象獲取網(wǎng)頁源碼 htmlText = document.html(); } catch (MalformedURLException e) { System.out.println('世界上最遙遠(yuǎn)的距離就是沒有網(wǎng),檢查設(shè)置!'); e.printStackTrace(); } catch (IOException e) { System.out.println('您的網(wǎng)絡(luò)連接打開失敗,請(qǐng)稍后重試!'); e.printStackTrace(); } return htmlText; } /** * 操作Dom對(duì)象獲取圖片地址 * @param document * Dom對(duì)象 * @return 圖片地址集合 */ public static List<String> getImgAddressByDom(Document document) { // 用于存儲(chǔ)圖片地址 List<String> imgAddress = new ArrayList<String>(); if (null != document) { // <img src='http://www.aoyou183.cn/bcjs/5670.html' alt='' width='' height=''/> // 獲取頁面上所有的圖片元素 Elements elements = document.getElementsByTag('img'); String imgSrc = ''; // 迭代獲取圖片地址 for (Element el : elements) {imgSrc = el.attr('src');// imgSrc的內(nèi)容不為空,并且以http://開頭if ((!imgSrc.isEmpty()) && imgSrc.startsWith('http://')) { // 將有效圖片地址添加到List中 imgAddress.add(imgSrc);} } } return imgAddress; } /** * 根據(jù)網(wǎng)絡(luò)URL下載文件 * @param url * 文件所在地址 * @param fileName * 指定下載后該文件的名字 * @param savePath * 文件保存根路徑 */ public static void downloadFileByUrl(String url, String fileName, String savePath) { URL urlObj = null; URLConnection conn = null; InputStream inputStream = null; BufferedInputStream bis = null; OutputStream outputStream = null; BufferedOutputStream bos = null; try { // 1.建立網(wǎng)絡(luò)連接 urlObj = new URL(url); // 2.打開網(wǎng)絡(luò)連接 conn = urlObj.openConnection(); // 設(shè)置超時(shí)間為3秒 conn.setConnectTimeout(3 * 1000); // 防止屏蔽程序抓取而返回403錯(cuò)誤 conn.setRequestProperty('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)'); // 3.得到輸入流 inputStream = conn.getInputStream(); bis = new BufferedInputStream(inputStream); // 文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) {saveDir.mkdirs(); } // 文件的絕對(duì)路徑 String filePath = savePath + File.separator + fileName; File file = new File(filePath); // 4. outputStream = new FileOutputStream(file); bos = new BufferedOutputStream(outputStream); byte[] b = new byte[1024]; int len = 0; while ((len = bis.read(b)) != -1) {bos.write(b, 0, len); } System.out.println('info:' + url + ' download success,fileRename=' + fileName); } catch (MalformedURLException e) { System.out.println('世界上最遙遠(yuǎn)的距離就是沒有網(wǎng),檢查設(shè)置'); System.out.println('info:' + url + ' download failure'); e.printStackTrace(); } catch (IOException e) { System.out.println('您的網(wǎng)絡(luò)連接打開失敗,請(qǐng)稍后重試!'); System.out.println('info:' + url + ' download failure'); e.printStackTrace(); } finally {// 關(guān)閉流 try {if (bis != null) {// 關(guān)閉字節(jié)緩沖輸入流 bis.close();}if (inputStream != null) {// 關(guān)閉字節(jié)輸入流 inputStream.close();}if (bos != null) {// 關(guān)閉字節(jié)緩沖輸出流 bos.close();}if (outputStream != null) {// 關(guān)閉字節(jié)輸出流 outputStream.close();} } catch (IOException e) {e.printStackTrace(); } } }}
測試
public static void main(String[] args) { // 1.確定網(wǎng)址 String url = 'http://www.cnblogs.com/Marydon20170307/p/7402871.html'; // 2.獲取該網(wǎng)頁的Dom對(duì)象 Document document = getHtmlDocument(url); // 3.獲取該網(wǎng)頁所有符合要求的圖片地址 List<String> imgAddresses = getImgAddressByDom(document); String imgName = ''; String imgType = ''; // 4.設(shè)置圖片保存路徑 String savePath = 'C:/Users/Marydon/Desktop'; // 5.批量下載圖片 for (String imgSrc : imgAddresses) { // 5.1圖片命名:圖片名用32位字符組成的唯一標(biāo)識(shí) imgName = UUID.randomUUID().toString().replace('-', ''); // 5.2圖片格式(類型) imgType = imgSrc.substring(imgSrc.lastIndexOf('.')); imgName += imgType; // 5.3下載該圖片 downloadFileByUrl(imgSrc, imgName, savePath); }}
以上就是Java 根據(jù)網(wǎng)絡(luò)URL獲取該網(wǎng)頁上面所有的img標(biāo)簽并下載圖片的詳細(xì)內(nèi)容,更多關(guān)于java 下載網(wǎng)絡(luò)圖片的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. AspNetCore&MassTransit Courier實(shí)現(xiàn)分布式事務(wù)的詳細(xì)過程2. 如何在jsp界面中插入圖片3. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析4. PHP循環(huán)與分支知識(shí)點(diǎn)梳理5. XML基本概念XPath、XSLT與XQuery函數(shù)介紹6. JS中map和parseInt的用法詳解7. jsp實(shí)現(xiàn)登錄界面8. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案9. ASP.NET泛型三之使用協(xié)變和逆變實(shí)現(xiàn)類型轉(zhuǎn)換10. jsp+servlet簡單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))
