简介:我们经常需要用到互联网上的一些共享资源,图片就是资源的一种,怎么把网页上的图片批量下载下来?有时候我们需要把网页上的图片下载下来,但网页上图片那么多,怎么下载我们想要的东西呢,如果这个网页都是我们想要 ...
我们经常需要用到互联网上的一些共享资源,图片就是资源的一种,怎么把网页上的图片批量下载下来?有时候我们需要把网页上的图片下载下来,但网页上图片那么多,怎么下载我们想要的东西呢,如果这个网页都是我们想要的图片,难道我们要一点一点一张一张右键下载吗? 当然不好,这里提供一段Java实现的网络爬虫抓图片代码,程序员同志有喜欢的记得收藏哦, 材料:必须会java开发,用到的核心jar Jsoup自己去网上下载很多。 以下是我已经实现的界面化的抓取图片的在线工具,有兴趣的朋友可以按照图片地址打开看看 下图是抓取效果网络上随便找第一个美女图片网站 这个是要抓取的网站的主界面: 这里是抓取的结果已经到我本地电脑了 下面是实现代码: /** *模拟用户请求 */ public final static String UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6821.400 QQBrowser/10.3.3040.400"; /* * *抓取全部图片地址 备注:zfilepath是zip文件路径 url是网页地址 pp是img的其中属性一般是src即可 */ public static boolean getImgSrc(String zfilepath,String url,String pp){ boolean isb =false; // 利用Jsoup获得连接 Connection connect = Jsoup.connect(url).timeout(5000); connect.header("Connection", "Keep-Alive"); connect.header("Content-Type", "application/x-www-form-urlencoded"); connect.header("Accept-Encoding", "gzip, deflate, sdch"); connect.header("Accept", "*/*"); connect.header("User-Agent",Const.UserAgent); ZipOutputStream out = null; try { // 得到Document对象 Document document = connect.ignoreContentType(true).timeout(5000).get(); // 查找所有img标签 Elements imgs = document.getElementsByTag("img"); File zipfile = new File(zfilepath); out=new ZipOutputStream(new FileOutputStream(zipfile)); int i=1; List<String> listimg = new ArrayList<String>(); for (Element element : imgs) { //获取每个img标签URL "abs:"表示绝对路径 String imgSrc = element.attr("abs:"+pp); listimg.add(imgSrc); } listimg = removeCf(listimg); if(listimg!=null && listimg.size()>0){ for(int x=0;x<listimg.size();x++){ long stime = System.currentTimeMillis(); String imgSrc =listimg.get(x); // 打印URL System.out.println(imgSrc); //下载图片到本地 boolean is = downImages(imgSrc,out); long etime = System.currentTimeMillis(); float alltime = (float)(etime - stime)/1000; Map<String,String> rest = new HashMap<String,String>(); rest.put("img",imgSrc); rest.put("time",(alltime)+""); rest.put("num",i+""); rest.put("status","true"); if(is){ rest.put("http","成功"); }else{ rest.put("http","失败"); } i++; } Map<String,String> rest1 = new HashMap<String,String>(); rest1.put("status","true"); rest1.put("msg","打包完成"); System.out.println("下载完成"); isb =true; }else{ Map<String,String> rest1 = new HashMap<String,String>(); rest1.put("status","true"); rest1.put("msg","未抓取到数据,有可能反爬虫了"); client.sendEvent("chatevent", rest1); } } catch (IOException e) { e.printStackTrace(); Map<String,String> rest = new HashMap<String,String>(); rest.put("status","false"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { if(out!=null){ out.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return isb; } /** * 下载图片到指定目录 * * @param filePath 文件路径 * @param imgUrl 图片URL */ public static boolean downImages(/*String filePath,*/ String imgUrl,ZipOutputStream outStream) { boolean is = false; // 若指定文件夹没有,则先创建 /* 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"); /** * 验证图片格式保证获取动态图片 */ fileName = vidImg(fileName); if(fileName.equals("")){ return is; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // 写出的路径 InputStream in = null; try { // 获取图片URL URL url = new URL(imgUrl); // 获得连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent",Const.UserAgent); // 设置10秒的相应时间 connection.setConnectTimeout(10 * 1000); // 获得输入流 in = connection.getInputStream(); byte[] data=readInputStream(in); outStream.putNextEntry(new ZipEntry(fileName)); outStream.write(data); is = true; return is; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { outStream.closeEntry(); in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return is; } /** * 去除重复的图片 * @param list * @return */ public static List<String> removeCf(List<String> list){ List<String> listTemp = new ArrayList<String> (); for(int i=0;i<list.size();i++){ if(!listTemp.contains(list.get(i))){ listTemp.add(list.get(i)); } } return listTemp; } 喜欢的记得收藏哦 这个工具我已经发布了,地址就是:http://www.yzcopen.com/img/imgdown 本文仅代表作者个人观点,不代表巅云官方发声,对观点有疑义请先联系作者本人进行修改,若内容非法请联系平台管理员,邮箱2522407257@qq.com。更多相关资讯,请到巅云www.yinxi.net学习互联网营销技术请到巅云建站www.yx10011.com。 |