利用jsoup抓取網頁圖片


jsoup簡介

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的操作方法來取出和操作數據。

官網

jsoup官網

代碼

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編碼會變為加號,再對其轉換為對應的%20


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM