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

妖狐艹你老母 2023-07-11 15:13 83阅读 0赞

添加jsoup依赖

  1. <dependency>
  2. <groupId>org.jsoup</groupId>
  3. <artifactId>jsoup</artifactId>
  4. <version>1.9.2</version>
  5. </dependency>
  6. package im.bide.utils;
  7. import org.jsoup.Connection;
  8. import org.jsoup.Jsoup;
  9. import org.jsoup.nodes.Document;
  10. import org.jsoup.nodes.Element;
  11. import org.jsoup.select.Elements;
  12. import java.io.*;
  13. import java.net.MalformedURLException;
  14. import java.net.URL;
  15. import java.net.URLConnection;
  16. import java.net.URLEncoder;
  17. public class FetchImgsUtil {
  18. /** * 下载图片到指定目录 *对爬虫感兴趣的 作者QQ1023732997(vx同号) * @param filePath 文件路径 * @param imgUrl 图片URL */
  19. public static void downImages(String filePath, String imgUrl) {
  20. // 若指定文件夹没有,则先创建
  21. File dir = new File(filePath);
  22. if (!dir.exists()) {
  23. dir.mkdirs();
  24. }
  25. // 截取图片文件名
  26. String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1, imgUrl.length());
  27. try {
  28. // 文件名里面可能有中文或者空格,所以这里要进行处理。但空格又会被URLEncoder转义为加号
  29. String urlTail = URLEncoder.encode(fileName, "UTF-8");
  30. // 因此要将加号转化为UTF-8格式的%20
  31. imgUrl = imgUrl.substring(0, imgUrl.lastIndexOf('/') + 1) + urlTail.replaceAll("\\+", "\\%20");
  32. } catch (UnsupportedEncodingException e) {
  33. e.printStackTrace();
  34. }
  35. // 写出的路径
  36. File file = new File(filePath + File.separator + fileName);
  37. try {
  38. // 获取图片URL
  39. URL url = new URL(imgUrl);
  40. // 获得连接
  41. URLConnection connection = url.openConnection();
  42. // 设置10秒的相应时间
  43. connection.setConnectTimeout(10 * 1000);
  44. // 获得输入流
  45. InputStream in = connection.getInputStream();
  46. // 获得输出流
  47. BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
  48. // 构建缓冲区
  49. byte[] buf = new byte[1024];
  50. int size;
  51. // 写入到文件
  52. while (-1 != (size = in.read(buf))) {
  53. out.write(buf, 0, size);
  54. }
  55. out.close();
  56. in.close();
  57. } catch (MalformedURLException e) {
  58. e.printStackTrace();
  59. } catch (IOException e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. public static void main(String[] args) {
  64. // 利用Jsoup获得连接
  65. Connection connect = Jsoup.connect("https://www.csdn.net/");
  66. try {
  67. // 得到Document对象
  68. Document document = connect.get();
  69. // 查找所有img标签
  70. Elements imgs = document.getElementsByTag("img");
  71. System.out.println("共检测到下列图片URL:");
  72. System.out.println("开始下载");
  73. // 遍历img标签并获得src的属性
  74. for (Element element : imgs) {
  75. //获取每个img标签URL "abs:"表示绝对路径
  76. String imgSrc = element.attr("abs:src");
  77. // 打印URL
  78. System.out.println(imgSrc);
  79. //下载图片到本地
  80. FetchImgsUtil.downImages("D:\\jsop\\img\\taobao", imgSrc);
  81. }
  82. System.out.println("下载完成");
  83. } catch (IOException e) {
  84. e.printStackTrace();
  85. }
  86. }
  87. }

发表评论

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

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

相关阅读