Java 下载指定网页的指定图片到本地电脑

Java 下载指定网页的指定图片到本地电脑

系统:Win10
IDE:IntelliJ IDEA 2017.3.7
JDK:1.8.0_121

1.功能需求

给一个指定网页链接,能够下载该网页上的指定图片到本地电脑的指定文件夹 - 例:下面框出来的图片 https://www.veer.com/topic/913/
在这里插入图片描述

2.实现分析

1.获取目标网页的源码
2.用正则匹配获取该网页内的所有 img 标签
3.提取需要的 img 标签的 src 属性
4.下载该 src 地址下的图片到本地

1):获取目标网页的源码,并打印出来

我们写一个获取该目标网页内容的方法

	// 获取html内容
	public static String getHTML(String targetUrl) throws Exception {
	    URL url = new URL(targetUrl);
	    URLConnection conn = url.openConnection();
	    conn.setRequestProperty("User-Agent", "Mozilla/5.0"); // 添加请求头
	    InputStream is = conn.getInputStream(); // 获取输入流
	    InputStreamReader isr = new InputStreamReader(is);
	    BufferedReader br = new BufferedReader(isr);
	    String line = null;
	    StringBuffer buffer = new StringBuffer();
	    while ((line = br.readLine()) != null) {
	        buffer.append(line);
	        buffer.append("\n");
	    }
	    br.close();
	    isr.close();
	    is.close();
	    return buffer.toString();
	}

并将内容打印到控制台查看

	public static void main(String[] args) throws Exception {
        String savePath = "images"; // 存储图片地址
        URL = "https://www.veer.com/topic/913/";
        String html = getHTML(URL);
        System.out.println(html);
    }

可以看到,该网页的源码已经打印出来了
在这里插入图片描述

2):用正则匹配获取该网页内的所有 img 标签,并打印出来

接下来,我们需要写一个符合要求的 img 标签的正则表达式(根据自己的需求,我这里的匹配所有的)

	// 获取 img 标签的正则表达式
    private static final String ImgTag_REG = "<img.*?src=[\\\"|\\']?(.*?)[\\\"|\\']?\\s.*?>";
	// 匹配所有符合要求的 img 标签
    public static List<String> getImageTag(String html) {
        Matcher matcher= Pattern.compile(ImgTag_REG).matcher(html);
        List<String> listImgTag=new ArrayList<String>();
        while (matcher.find()){
            listImgTag.add(matcher.group());
        }
        return listImgTag;
    }

可以看到,匹配好的 img 标签已经打印出来了
在这里插入图片描述

3):提取需要的 img 标签的 src 属性,并打印出来

接下来,写一个合适的 src 正则表达式,这里需要一点正则表达式的基础了,我这里匹配的是:包含 :// 的 src 属性

	// 获取 src 属性的正则表达式
    private static final String ImgSrc_REG = "[a-zA-z]+://[^\\s]*";
	// 获取 img 标签里需要的 src 属性值
    public static String getImageSrc(String imgTag) {
        String imgSrc = "";
        Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(imgTag);
        while (matcher.find()) {
            imgSrc=matcher.group().substring(0,matcher.group().length() - 1);
            return imgSrc;
        }
        return imgSrc;
    }

我们已经把需要的 src 属性打印出来了,然后我们根据这个图片的地址,即可批量下载图片至本地
在这里插入图片描述

4):下载该 src 地址下的图片到本地

我们写一个根据 imgSrc,filename,savaPath 下载图片的方法( imgSrc:img 标签的 src属性;filename:文件的保存名称;savePath:文件的保存路径 )

	// 根据 imgSrc 下载图片,保存到指定位置
    private static void Download(String imgSrc,String filename, String savePath) throws Exception{
        try {
            URL uri = new URL(imgSrc);
            URLConnection conn = uri.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/5.0"); // 添加请求头
            InputStream in = conn.getInputStream();;
            FileOutputStream fo = new FileOutputStream(new File(savePath+"\\"+filename));// 文件输出流
            byte[] buf = new byte[1024];
            int length = 0;
            while ((length = in.read(buf, 0, buf.length)) != -1) {
                fo.write(buf, 0, length);
            }
            // 关闭流
            in.close();
            fo.close();
            System.out.println(filename + "下载完成");

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(imgSrc + "图片下载失败");
            return;
        }
    }

这里再补上一个 main 函数

	public static void main(String[] args) throws Exception {
        String savePath = "images"; // 存储图片地址
        URL = "https://www.veer.com/topic/913/";
        String html = getHTML(URL);
        List<String> imgList = getImageTag(html);
        for (int i = 1,j = 1;i<imgList.size();i++) {
            try {
                String imgSrc = getImageSrc(imgList.get(i));
                if ("".equals(imgSrc)||imgSrc == null){
                    continue;
                }else{
                    filename = j+".jpg";
                    Download(imgSrc, filename, savePath);
                    j++;
                }
            }
            catch (Exception e){
                e.printStackTrace();
                break;
            }
        }
    }

最后可以看到我们成功下载 98 个图片至本地项目的 images 文件夹内
在这里插入图片描述

3.结果确认

我们进入对应文件夹内,可以看到图片确实已经下载完成。
在这里插入图片描述

4.源码地址

GitHub地址:https://github.com/1123GY/JavaDemo

猜你喜欢

转载自blog.csdn.net/qq_35132089/article/details/107360555
今日推荐