图片获取

图片获取

package com.hzh.image;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;

public class GetImage {

    public void getDoc() throws IOException {

        String path="D:/image/";

        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }
        Document doc = Jsoup.connect("http://www.jj20.com/bz/ktmh/ktmx/5064.html").get();
        // 获取后缀为png和jpg的图片的元素集合<img src="">aaa</img>
        Elements pngs = doc.select("img[src]");
        System.out.println(pngs.size());
        // 遍历元素
        for (Element e : pngs) {
            System.out.println(e);
            String src = e.attr("src");// 获取img中的src路径
            // 获取后缀名
            String imageName = src.substring(src.lastIndexOf("/") + 1, src.length());
//          System.out.println(src);
            if(!src.contains("http")){
                src = src.replace("//img", "http://img");
            }
//          System.out.println(srcnew);
//          System.out.println(imageName);
            try {
                // 连接url
                URL url = new URL(src);
                URLConnection uri = url.openConnection();
                // 获取数据流
                InputStream is = uri.getInputStream();
                // 写入数据流
                OutputStream os = new FileOutputStream(new File(path, imageName));

                byte[] buf = new byte[1024];
                int l = 0;
                while ((l = is.read(buf)) != -1) {
                    os.write(buf, 0, l);
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
    @Test
    public void downPic() throws IOException {
        new GetImage().getDoc(); // 调用方法
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42430194/article/details/80728338