利用Jsoup解析HTML页面并下载文件到指定文件夹

1.在pom文件里面添加依赖:

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.8.3</version>
</dependency>

2.要下载的文件目录地址如下:

 

 

2.使用url 下载远程文件工具类

package com.longjin.comm.utils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:使用url 下载远程文件
 * @Author 何志鹏
 * @Date 2020/6/11 18:20
 * @Version 1.0
 */
public class JsoupByFileUtils {
    /**
     * description: 使用url 下载远程文件
     * @param urlPath  --- url资源
     * @param targetDirectory --- 目标文件夹
     * @param name--- 自定义的文件名称
     * @throws Exception
     * @return void
     * @version v1.0
     * @author zhangcw
     * @date 2019年9月3日 下午8:29:01
     */
    public static void download(String urlPath , String targetDirectory,String name) throws Exception {
        // 解决url中可能有中文情况
        System.out.println("url:"+ urlPath);
        URL url = new URL(urlPath);
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        http.setConnectTimeout(3000);
        // 设置 User-Agent 避免被拦截
        http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
        String contentType = http.getContentType();
        System.out.println("contentType: "+ contentType);
        // 获取文件大小
        long length = http.getContentLengthLong();
        System.out.println("文件大小:"+(length / 1024)+"KB");
        // 获取文件名
        String fileName = getFileName(http , urlPath);
        String newName = name;
        InputStream inputStream = http.getInputStream();
        byte[] buff = new byte[1024*10];
        File file=new File(targetDirectory,newName);
        OutputStream out = new FileOutputStream(file);
        int len ;
        int count = 0; // 计数
        while((len = inputStream.read(buff)) != -1) {
            out.write(buff, 0, len);
            out.flush();
            ++count ;
        }
        System.out.println("count:"+ count);
        // 关闭资源
        out.close();
        inputStream.close();
        http.disconnect();
    }

    /**
     * description: 获取文件名
     * @param http
     * @param urlPath
     * @throws UnsupportedEncodingException
     * @return String
     * @version v1.0
     * @author w
     * @date 2019年9月3日 下午8:25:55
     */
    private static String getFileName(HttpURLConnection http , String urlPath) throws UnsupportedEncodingException {
        String headerField = http.getHeaderField("Content-Disposition");
        String fileName = null ;
        if(null != headerField) {
            String decode = URLDecoder.decode(headerField, "UTF-8");
            fileName = decode.split(";")[1].split("=")[1].replaceAll("\"", "");
            System.out.println("文件名是: "+ fileName);
        }
        if(null == fileName) {
            // 尝试从url中获取文件名
            String[] arr  = urlPath.split("/");
            fileName = arr[arr.length - 1];
            System.out.println("url中获取文件名:"+ fileName);
        }
        return fileName;
    }
    
}

3.main方法jsoup解析页面下载文件  代码如下:

public static void main(String[] args) throws  Exception{
    //下载网址的url地址
    Document doc = Jsoup.connect("要下载的地址").get();
    Elements a = doc.getElementsByTag("a");
    Map<String,String> map = new HashMap<>();
    for (Element element : a) {
        if (element.html().contains("Directory")) {
            continue;
        }
        Document document = Jsoup.connect("要下载的地址" + element.html()).get();
        Elements fileSrcs = document.getElementsByTag("a");
        for (Element fileSrc : fileSrcs) {
            map.put(fileSrc.html(),"域名地址"+fileSrc.attr("href"));
            System.err.println("下载的文件名称========================="+fileSrc.html());
        }
    }
    for(Map.Entry<String,String> ma :map.entrySet()){
        download(ma.getValue(), "D:/TEST",ma.getKey());
    }

}

 

4.下载到本地TEST目录的文件如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值