Jsoup爬取网站图片

谁践踏了优雅 2023-01-21 13:23 343阅读 0赞

Jsoup 是一款 Java 的 HTML 解析器,我们可以用它进行网站图片的爬取,然后下载到本地文件夹中。
首先在pom.xml中添加依赖。

  1. <dependency>
  2. <groupId>org.jsoup</groupId>
  3. <artifactId>jsoup</artifactId>
  4. <version>1.10.2</version>
  5. </dependency>

首先我们写出下载图片的方法,先创建一个文件夹,然后截取出图片的文件名,并对文件名进行处理并转换为UTF-8格式。

  1. public static void downImages(String filePath, String imgUrl) {
  2. // 若没有指定文件夹,则先创建
  3. File dir = new File(filePath);
  4. if (!dir.exists()) {
  5. dir.mkdirs();
  6. }
  7. // 截取图片文件名
  8. String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1, imgUrl.length());
  9. try {
  10. // 文件名里面可能有中文或者空格,所以这里要进行处理。但空格又会被URLEncoder转义为加号
  11. String urlTail = URLEncoder.encode(fileName, "UTF-8");
  12. // 因此要将加号转化为UTF-8格式
  13. imgUrl = imgUrl.substring(0, imgUrl.lastIndexOf('/') + 1) + urlTail.replaceAll("\\+", "\\%20");
  14. } catch (UnsupportedEncodingException e) {
  15. e.printStackTrace();
  16. }
  17. // 写出的路径
  18. File file = new File(filePath + File.separator + fileName);
  19. try {
  20. // 获取图片URL
  21. URL url = new URL(imgUrl);
  22. // 获得连接
  23. URLConnection connection = url.openConnection();
  24. // 设置10秒的相应时间
  25. connection.setConnectTimeout(10 * 1000);
  26. // 获得输入流
  27. InputStream in = connection.getInputStream();
  28. // 获得输出流
  29. BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
  30. // 构建缓冲区
  31. byte[] buf = new byte[1024];
  32. int size;
  33. // 写入到文件
  34. while (-1 != (size = in.read(buf))) {
  35. out.write(buf, 0, size);
  36. }
  37. out.close();
  38. in.close();
  39. } catch (MalformedURLException e) {
  40. e.printStackTrace();
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. }
  44. }

然后使用Jsoup连接到网页,将图片下载到本地文件夹中。

  1. public static void main(String[] args) {
  2. // 利用Jsoup获得连接
  3. Connection connect = Jsoup.connect("https://pic.netbian.com/4kqiche/");
  4. try {
  5. // 得到Document对象
  6. Document document = connect.get();
  7. // 查找所有img标签
  8. Elements imgs = document.getElementsByTag("img");
  9. System.out.println("共检测到下列图片URL:");
  10. System.out.println("开始下载");
  11. // 遍历img标签并获得src的属性
  12. for (Element element : imgs) {
  13. //获取每个img标签URL "abs:"表示绝对路径
  14. String imgSrc = element.attr("abs:src");
  15. // 打印URL
  16. System.out.println(imgSrc);
  17. //下载图片到本地
  18. img.downImages("f:/img", imgSrc);
  19. }
  20. System.out.println("下载完成");
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. }

运行结果:
在这里插入图片描述

图片也已经下载到本地文件夹中了
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,343人围观)

还没有评论,来说两句吧...

相关阅读

    相关 jsoup网站内容

    soup爬取网站内容,感觉是一件很神奇的事。如果爬取的内容进行非法的传播或进行商业用途,可能会收到法院的传票(被仲裁),所以请确认你的用途,以免官司或牢狱之苦。总而言之,...