栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 根据网络URL获取该网页上面所有的img标签并下载图片

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 根据网络URL获取该网页上面所有的img标签并下载图片

说明:根据网络URL获取该网页上面所有的img标签并下载符合要求的所有图片

所需jar包:jsoup.jar

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.jsoup.Jsoup;
import org.jsoup.nodes.document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public class ImgDownloadUtil {

  
  public static document getHtmldocument(String url) {
    document document = null;
    URL urlObj = null;
    try {
      // 1.建立网络连接
      urlObj = new URL(url);
      // 2.根据url获取document对象
      document = Jsoup.parse(urlObj, 5000);// 单位:毫秒超时时间

    } catch (MalformedURLException e) {
      System.out.println("世界上最遥远的距离就是没有网,检查设置!");
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("您的网络连接打开失败,请稍后重试!");
      e.printStackTrace();
    }

    return document;
  }

  
  public static String getHtmlText(String url) {
    String htmlText = "";
    document document = null;
    URL urlObj = null;
    try {
      // 1.建立网络连接
      urlObj = new URL(url);
      // 2.根据url获取document对象
      document = Jsoup.parse(urlObj, 5000);// 单位:毫秒超时时间
      // 3.根据dom对象获取网页源码
      htmlText = document.html();
    } catch (MalformedURLException e) {
      System.out.println("世界上最遥远的距离就是没有网,检查设置!");
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("您的网络连接打开失败,请稍后重试!");
      e.printStackTrace();
    }

    return htmlText;
  }

  
  public static List getImgAddressByDom(document document) {
    // 用于存储图片地址
    List imgAddress = new ArrayList();
    if (null != document) {
      // 
      // 获取页面上所有的图片元素
      Elements elements = document.getElementsByTag("img");
      String imgSrc = "";
      // 迭代获取图片地址
      for (Element el : elements) {
 imgSrc = el.attr("src");
 // imgSrc的内容不为空,并且以http://开头
 if ((!imgSrc.isEmpty()) && imgSrc.startsWith("http://")) {
   // 将有效图片地址添加到List中
   imgAddress.add(imgSrc);
 }
      }
    }

    return imgAddress;
  }

  
  public static void downloadFileByUrl(String url, String fileName, String savePath) {
    URL urlObj = null;
    URLConnection conn = null;
    InputStream inputStream = null;
    BufferedInputStream bis = null;
    OutputStream outputStream = null;
    BufferedOutputStream bos = null;
    try {
      // 1.建立网络连接
      urlObj = new URL(url);
      // 2.打开网络连接
      conn = urlObj.openConnection();
      // 设置超时间为3秒
      conn.setConnectTimeout(3 * 1000);
      // 防止屏蔽程序抓取而返回403错误
      conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
      // 3.得到输入流
      inputStream = conn.getInputStream();
      bis = new BufferedInputStream(inputStream);

      // 文件保存位置
      File saveDir = new File(savePath);
      if (!saveDir.exists()) {
 saveDir.mkdirs();
      }
      // 文件的绝对路径
      String filePath = savePath + File.separator + fileName;
      File file = new File(filePath);
      // 4.
      outputStream = new FileOutputStream(file);
      bos = new BufferedOutputStream(outputStream);
      byte[] b = new byte[1024];
      int len = 0;
      while ((len = bis.read(b)) != -1) {
 bos.write(b, 0, len);
      }
      System.out.println("info:" + url + " download success,fileRename=" + fileName);
    } catch (MalformedURLException e) {
      System.out.println("世界上最遥远的距离就是没有网,检查设置");
      System.out.println("info:" + url + " download failure");
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("您的网络连接打开失败,请稍后重试!");
      System.out.println("info:" + url + " download failure");
      e.printStackTrace();
    } finally {// 关闭流
      try {
 if (bis != null) {// 关闭字节缓冲输入流
   bis.close();
 }

 if (inputStream != null) {// 关闭字节输入流
   inputStream.close();
 }
 if (bos != null) {// 关闭字节缓冲输出流
   bos.close();
 }
 if (outputStream != null) {// 关闭字节输出流
   outputStream.close();
 }

      } catch (IOException e) {
 e.printStackTrace();
      }
    }
  }

}

测试

public static void main(String[] args) {
  // 1.确定网址
  String url = "http://www.cnblogs.com/Marydon20170307/p/7402871.html";
  // 2.获取该网页的Dom对象
  document document = getHtmldocument(url);
  // 3.获取该网页所有符合要求的图片地址
  List imgAddresses = getImgAddressByDom(document);
  String imgName = "";
  String imgType = "";
  // 4.设置图片保存路径
  String savePath = "C:/Users/Marydon/Desktop";
  // 5.批量下载图片
  for (String imgSrc : imgAddresses) {
    // 5.1图片命名:图片名用32位字符组成的唯一标识
    imgName = UUID.randomUUID().toString().replace("-", "");
    // 5.2图片格式(类型)
    imgType = imgSrc.substring(imgSrc.lastIndexOf("."));
    imgName += imgType;
    // 5.3下载该图片
    downloadFileByUrl(imgSrc, imgName, savePath);
  }
}

以上就是Java 根据网络URL获取该网页上面所有的img标签并下载图片的详细内容,更多关于java 下载网络图片的资料请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/130684.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号