JAVA Jsoup爬取网页图片下载到本地

添加jsoup依赖

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.9.2</version>
</dependency>
package im.bide.utils;

import org.jsoup.Connection;
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.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class FetchImgsUtil {
    /**
     * 下载图片到指定目录
     *对爬虫感兴趣的 作者QQ1023732997(vx同号)
     * @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("https://www.csdn.net/");
        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:\\jsop\\img\\taobao", imgSrc);
            }
            System.out.println("下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
使用Jsoup爬取分页数据的步骤如下: 1. 定义要爬取的网页地址和需要爬取的内容。 2. 使用Jsoup连接网页,获取网页内容。 3. 使用Jsoup解析网页内容,提取需要的数据。 4. 如果网页中存在多页数据,使用循环遍历所有网页,重复步骤2和步骤3。 5. 将提取的数据保存到本地或数据库中。 下面是一个示例代码,演示如何使用Jsoup爬取分页数据: ```java import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class PageCrawler { public static void main(String[] args) throws IOException { // 定义要爬取的网页地址和需要爬取的内容 String url = "https://example.com/page/1"; String cssSelector = ".list-item"; // 使用Jsoup连接网页,获取网页内容 Document doc = Jsoup.connect(url).get(); // 使用Jsoup解析网页内容,提取需要的数据 Elements items = doc.select(cssSelector); for (Element item : items) { // 处理每个数据项 String title = item.select(".title").text(); String description = item.select(".description").text(); System.out.println(title); System.out.println(description); System.out.println("------------"); } // 如果网页中存在多页数据,使用循环遍历所有网页 for (int i = 2; i <= 10; i++) { String nextUrl = "https://example.com/page/" + i; doc = Jsoup.connect(nextUrl).get(); items = doc.select(cssSelector); for (Element item : items) { // 处理每个数据项 String title = item.select(".title").text(); String description = item.select(".description").text(); System.out.println(title); System.out.println(description); System.out.println("------------"); } } // 将提取的数据保存到本地或数据库中 // ... } } ``` 在示例代码中,我们首先定义了要爬取的网页地址和需要爬取的内容。 然后,我们使用Jsoup连接网页,获取网页内容,并使用Jsoup解析网页内容,提取需要的数据。 如果网页中存在多页数据,我们使用循环遍历所有网页,重复步骤2和步骤3。 最后,我们可以将提取的数据保存到本地或数据库中。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云上上云

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值