jsoup is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods.
jsoup 是一款Java 的HTML解析器,可直接解析某個URL地址、HTML文本內容。它提供了一套很是省力的API,可經過DOM,CSS以及相似於jQuery的操做方法來取出和操做數據。java
jsoup官網node
import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; public class FetchImgsUtil { /** * 下載圖片到指定目錄 * * @param filePath 文件路徑 * @param imgUrl 圖片URL */ public static void downImages(String filePath, String imgUrl) { // 若指定文件夾沒有,則先建立 File dir = new File(filePath); if (!dir.exists()) { dir.mkdirs(); } // 截取圖片文件名 String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1, imgUrl.length()); try { // 文件名裏面可能有中文或者空格,因此這裏要進行處理。但空格又會被URLEncoder轉義爲加號 String urlTail = URLEncoder.encode(fileName, "UTF-8"); // 所以要將加號轉化爲UTF-8格式的%20 imgUrl = imgUrl.substring(0, imgUrl.lastIndexOf('/') + 1) + urlTail.replaceAll("\\+", "\\%20"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // 寫出的路徑 File file = new File(filePath + File.separator + fileName); try { // 獲取圖片URL URL url = new URL(imgUrl); // 得到鏈接 URLConnection connection = url.openConnection(); // 設置10秒的相應時間 connection.setConnectTimeout(10 * 1000); // 得到輸入流 InputStream in = connection.getInputStream(); // 得到輸出流 BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); // 構建緩衝區 byte[] buf = new byte[1024]; int size; // 寫入到文件 while (-1 != (size = in.read(buf))) { out.write(buf, 0, size); } out.close(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { // 利用Jsoup得到鏈接 Connection connect = Jsoup.connect("http://www.qq.com"); try { // 獲得Document對象 Document document = connect.get(); // 查找全部img標籤 Elements imgs = document.getElementsByTag("img"); System.out.println("共檢測到下列圖片URL:"); System.out.println("開始下載"); // 遍歷img標籤並得到src的屬性 for (Element element : imgs) { //獲取每一個img標籤URL "abs:"表示絕對路徑 String imgSrc = element.attr("abs:src"); // 打印URL System.out.println(imgSrc); //下載圖片到本地 FetchImgsUtil.downImages("d:/img", imgSrc); } System.out.println("下載完成"); } catch (IOException e) { e.printStackTrace(); } } }
剛開始的時候有的圖片URL中文件名包含了中文、空格等,致使了異常如:java.io.IOException: Server returned HTTP response code: 500 for URL: http://images.csdn.net/20170301/程序員1703封面.jpg
多是編碼的影響,所以須要對圖片文件名轉換爲UTF-8格式,而且要注意空格通過URLEncoder編碼會變爲加號,再對其轉換爲對應的%20jquery