zoukankan      html  css  js  c++  java
  • 利用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

  • 相关阅读:
    QuantLib 金融计算
    【翻译】《理解收益率曲线》系列
    QuantLib 金融计算——C++ 代码改写成 Python 程序的一些经验
    可转债研报阅读笔记
    SWIG 3 中文手册——13. 约定
    SWIG 3 中文手册——12. 自定义功能
    SWIG 3 中文手册——11. 类型映射
    【翻译】Quant 应该怎样写博客?
    QuantLib 金融计算——案例之普通利率互换分析(2)
    仿射期限结构模型:理论与实现——实现部分
  • 原文地址:https://www.cnblogs.com/zyoung/p/6579963.html
Copyright © 2011-2022 走看看