1. package com.enation.newtest;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. import java.net.URLConnection;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. import java.util.regex.Matcher;
  14. import java.util.regex.Pattern;
  15.  
  16. import org.apache.commons.lang3.StringEscapeUtils;
  17. import org.jsoup.Jsoup;
  18. import org.jsoup.nodes.Document;
  19.  
  20. // 爬取网易首页所有图片
  21. public class Jsoup163 {
  22.  
  23. public static void main(String[] args) throws Exception{
  24. String downloadPath = "D:\\360Downloads\\test";
  25. List<String> list = nameList("网易--首页");
  26. getPictures(list,1,downloadPath); //1代表下载一页,一页一般有30张图片
  27. }
  28.  
  29. public static void getPictures(List<String> keywordList, int max,String downloadPath) throws Exception{ // key为关键词,max作为爬取的页数
  30. String gsm=Integer.toHexString(max)+"";
  31. String finalURL = "";
  32. String tempPath = "";
  33. for(String keyword : keywordList){
  34. tempPath = downloadPath;
  35. if(!tempPath.endsWith("\\")){
  36. tempPath = downloadPath+"\\";
  37. }
  38. tempPath = tempPath+keyword+"\\";
  39. File f = new File(tempPath);
  40. if(!f.exists()){
  41. f.mkdirs();
  42. }
  43. int picCount = 1;
  44. for(int page=1;page<=max;page++) {
  45. sop("正在下载第"+page+"页面");
  46. Document document = null;
  47. try {
  48. String url ="http://www.163.com/";
  49. sop(url);
  50. document = Jsoup.connect(url).data("query", "Java")//请求参数
  51. .userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)")//设置urer-agent get();
  52. .timeout(5000)
  53. .get();
  54. String xmlSource = document.toString();
  55. xmlSource = StringEscapeUtils.unescapeHtml3(xmlSource);
  56. //sop(xmlSource);
  57. String reg = "<img.*src=(.*?)[^>]*?>";
  58. String reg2 = "src\\s*=\\s*\"?(.*?)(\"|>|\\s+)";
  59. String reg2datasrc = "data-src\\s*=\\s*\"?(.*?)(\"|>|\\s+)";
  60.  
  61. Pattern pattern = Pattern.compile(reg);
  62. Pattern pattern2 = Pattern.compile(reg2);
  63. Pattern pattern2datasrc = Pattern.compile(reg2datasrc);
  64.  
  65. Matcher m = pattern.matcher(xmlSource);
  66. while (m.find()){
  67. finalURL = m.group();
  68. System.out.println(finalURL);
  69. Matcher m2 = null;
  70. if(finalURL.indexOf("data-src")>0){
  71. m2 = pattern2datasrc.matcher(finalURL);
  72. }else {
  73. m2 = pattern2.matcher(finalURL);
  74. }
  75. if(m2.find()){
  76. finalURL = m2.group(1);
  77. System.out.println(finalURL);
  78. if(finalURL.startsWith("http")){
  79. sop(keyword+picCount+++":"+finalURL);
  80. download(finalURL,tempPath);
  81. sop(" 下载成功");
  82. }
  83. }
  84. }
  85. } catch (IOException e) {
  86. e.printStackTrace();
  87. }
  88. }
  89. }
  90. sop("下载完毕");
  91. delMultyFile(downloadPath);
  92. sop("已经删除所有空图");
  93. }
  94. public static void delMultyFile(String path){
  95. File file = new File(path);
  96. if(!file.exists())
  97. throw new RuntimeException("File \""+path+"\" NotFound when excute the method of delMultyFile()....");
  98. File[] fileList = file.listFiles();
  99. File tempFile=null;
  100. for(File f : fileList){
  101. if(f.isDirectory()){
  102. delMultyFile(f.getAbsolutePath());
  103. }else{
  104. if(f.length()==0)
  105. sop(f.delete()+"---"+f.getName());
  106. }
  107. }
  108. }
  109. public static List<String> nameList(String nameList){
  110. List<String> arr = new ArrayList<String>();
  111. String[] list;
  112. if(nameList.contains(","))
  113. list= nameList.split(",");
  114. else if(nameList.contains("、"))
  115. list= nameList.split("、");
  116. else if(nameList.contains(" "))
  117. list= nameList.split(" ");
  118. else{
  119. arr.add(nameList);
  120. return arr;
  121. }
  122. for(String s : list){
  123. arr.add(s);
  124. }
  125. return arr;
  126. }
  127. public static void sop(Object obj){
  128. System.out.println(obj);
  129. }
  130. //根据图片网络地址下载图片
  131. public static void download(String url,String path){
  132. //path = path.substring(0,path.length()-2);
  133. File file= null;
  134. File dirFile=null;
  135. FileOutputStream fos=null;
  136. HttpURLConnection httpCon = null;
  137. URLConnection con = null;
  138. URL urlObj=null;
  139. InputStream in =null;
  140. byte[] size = new byte[1024];
  141. int num=0;
  142. try {
  143. String downloadName= url.substring(url.lastIndexOf("/")+1);
  144. dirFile = new File(path);
  145. if(!dirFile.exists() && path.length()>0){
  146. if(dirFile.mkdir()){
  147. sop("creat document file \""+path.substring(0,path.length()-1)+"\" success...\n");
  148. }
  149. }else{
  150. file = new File(path+downloadName);
  151. fos = new FileOutputStream(file);
  152. if(url.startsWith("http")){
  153. urlObj = new URL(url);
  154. con = urlObj.openConnection();
  155. httpCon =(HttpURLConnection) con;
  156. int responseCode = httpCon.getResponseCode();
  157. if(responseCode == 200){
  158. in = httpCon.getInputStream();
  159. while((num=in.read(size)) != -1){
  160. for(int i=0;i<num;i++)
  161. fos.write(size[i]);
  162. }
  163. }else {
  164. System.out.println("状态码:"+responseCode+" 地址:"+url);
  165. }
  166. }
  167. }
  168. }catch (FileNotFoundException notFoundE) {
  169. sop("找不到该网络图片....");
  170. }catch(NullPointerException nullPointerE){
  171. sop("找不到该网络图片....");
  172. }catch(IOException ioE){
  173. sop("产生IO异常.....");
  174. }catch (Exception e) {
  175. e.printStackTrace();
  176. }finally{
  177. try {
  178. if(fos!=null){
  179. fos.close();
  180. }
  181. } catch (Exception e) {
  182. e.printStackTrace();
  183. }
  184. }
  185. }
  186. }

其中,关键点在于获取图片img标签的正则表达式和图片的链接地址

String reg = "<img.*src=(.*?)[^>]*?>";
String reg2 = "src\\s*=\\s*\"?(.*?)(\"|>|\\s+)";

运行结果:

使用Jsoup 爬取网易首页所有的图片的更多相关文章

  1. Jsoup爬取带登录验证码的网站

    今天学完爬虫之后想的爬一下我们学校的教务系统,可是发现登录的时候有验证码.因此研究了Jsoup爬取带验证码的网站: 大体的思路是:(需要注意的是__VIEWSTATE一直变化,所以我们每个页面都需要重 ...

  2. Python爬虫实战教程:爬取网易新闻

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: Amauri PS:如有需要Python学习资料的小伙伴可以加点击 ...

  3. 如何利用python爬取网易新闻

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: LSGOGroup PS:如有需要Python学习资料的小伙伴可以 ...

  4. jsoup爬取某网站安全数据

    jsoup爬取某网站安全数据 package com.vfsd.net; import java.io.IOException; import java.sql.SQLException; impor ...

  5. Python爬虫实战教程:爬取网易新闻;爬虫精选 高手技巧

    前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. stars声明很多小伙伴学习Python过程中会遇到各种烦恼问题解决不了.为 ...

  6. 初识python 之 爬虫:爬取某网站的壁纸图片

    用到的主要知识点:requests.get 获取网页HTMLetree.HTML 使用lxml解析器解析网页xpath 使用xpath获取网页标签信息.图片地址request.urlretrieve ...

  7. python连续爬取多个网页的图片分别保存到不同的文件夹

      python连续爬取多个网页的图片分别保存到不同的文件夹 作者:vpoet mail:vpoet_sir@163.com #coding:utf-8 import urllib import ur ...

  8. Python爬取贴吧中的图片

    #看到贴吧大佬在发图,准备盗一下 #只是爬取一个帖子中的图片 1.先新建一个scrapy项目 scrapy startproject TuBaEx 2.新建一个爬虫 scrapy genspider ...

  9. Python 爬取煎蛋网妹子图片

    #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-08-24 10:17:28 # @Author : EnderZhou (z ...

随机推荐

  1. 第三十七章 springboot+docker(手动部署)

    一.下载centos镜像 docker pull hub.c.163.com/library/centos:latest docker tag containId centos:7 docker ru ...

  2. WCF三种通信模式

    WCF在通信过程中有三种模式:请求与答复.单向.双工通信. 请求与答复模式 描述:客户端发送请求,然后一直等待服务端的响应(异步调用除外),期间处于假死状态,直到服务端有了答复后才能继续执行其他程序 ...

  3. (转)VS2010启动调试时老是提示正在下载公共符号

      VS2010启动调试时老是提示正在下载公共符号,下载一些.dll文件,点取消后也能继续调试,但特别慢. 解决方法:工具—选项,或者调试—选项和设置,将调试下的“启用 .NET Framework  ...

  4. fragment 碎片整理

    activity_m1.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xm ...

  5. MFC下无法为空间添加变量解决

    许久不用MFC,今天在vs2008下用MFC写个小东西,结果在为控件添加变量的时候,居然无法成功——那个界面显示怪怪的,点击完成提示失败.    还好同事遇到过这个问题,给出链接http://hi.b ...

  6. jqyery dataTable 基本用法

    一:官方网站:[http://www.datatables.net/] 二:基本使用:[http://www.guoxk.com/node/jquery-datatables] 1.DataTable ...

  7. 乐视云计算基于OpenStack的IaaS实践

    本文作者岳龙广,现在就职于乐视云计算有限公司,负责IaaS部门的工作. 从开始工作就混在开源世界里,在虚拟化方面做过CloudStack/Ovirt开发,现在是做以OpenStack为基础的乐视云平台 ...

  8. MapReduce几个简单的例子

    文件合并和去重: 可以把每一行文本作为key,value为随意值. 数字排序: MapReduce过程中就有排序,它是按照key值进行排序的,如果key为封装int的IntWritable类型,那么M ...

  9. ADO.NET Entity Framework学习笔录(一)

    今天开始学习了EF的相关内容,以前只知道ADO.NET,今天学习后觉得有必要写个相关的学习心得,今天就先写第一篇. 我们的再学习的过程中所用到的环境是Windows7+SQLServer2008+VS ...

  10. CodeIgnitor 创建admin和其他目录,前后端分离,很巧妙的方式,网上查找其他的都不是使用这种方式实现的。

    在index.php的第97和98行的注释, // The directory name, relative to the "controllers" folder. Leave ...