java爬虫实战简单用Jsoup框架进行网页爬虫(如抓取网页图片)

首先去下载Jsoup的jar包,直接百度搜索下载就行了,我下载的jar包版本是1.10.3,然后导入jar包。

我的程序目录结构是这样的。


我现在要抓取的是http://www.nipic.com/photo/jingguan/shanshui/index.html这个网站的摄影图库中的所有风景图片,其中该图库中的图片有2010页,每页有20张图片,所以我要获取40200张图片,把这些图片全弄到本地磁盘,并且图片还可以查看的,数据也不能丢失。由于本文的着重点不是网页方面的知识而是爬虫方面的,所以这里就不说关于html和css等其他方面的知识了。根据浏览器的开发人员工具研究下要抓取的页面的内容。本文主要通过以下代码供大家学习,可以了解Jsoup框架怎么使用,用途在哪。

因为时间关系所以我代码健壮性没去考虑,大家想深入的可以自己去优化下代码,我的代码如下:

package com.jiaxun.spider;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JsoupSpider {

	// http://www.nipic.com/photo/jingguan/shanshui/index.html?page= 后面的数字逐个加1
	// 直到2010
	public static String getAllURL(String url) {
		StringBuffer sb = null;
		try {
			sb = new StringBuffer();
			for (int i = 1; i <= 2010; i++) {
				sb.append(url + i).append("\r\n");
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
		return sb.toString();
	}

	// 在大图的网址获取详细的图片地址
	public static String getPicURL(String picHrefUrl) {
		String picURL = null;
		if (picHrefUrl != null) {
			try {
				Document doc = Jsoup.connect(picHrefUrl).get();
				Element element = doc.getElementById("J_worksImg");
				picURL = element.attr("src");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				new RuntimeException(" ");
			}
		}
		return picURL;
	}

	// 下载图片到本地磁盘
	public static void downloadPicToLocal(String picSourceURL, String picDestPath) {
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		try {
			URL url = new URL(picSourceURL);
			bis = new BufferedInputStream(url.openStream());
			bos = new BufferedOutputStream(new FileOutputStream(picDestPath));
			byte[] b = new byte[1024 * 1024];
			int len = 0;
			while ((len = bis.read(b)) != -1) {
				bos.write(b, 0, len);
				bos.flush();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			new RuntimeException(" ");
		} finally {
			try {
				bos.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
			try {
				bis.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
		}
	}

	// 获取文件后缀名
	public static String getNameExtension(String picURL) {
		String extension = null;

		try {
			int lastIndexOf = 0;
			if (picURL != null && !picURL.equals("")) {
				if (picURL.endsWith(".jpg"))
					lastIndexOf = picURL.lastIndexOf(".jpg");
				if (picURL.endsWith(".png"))
					lastIndexOf = picURL.lastIndexOf(".png");
				extension = picURL.substring(lastIndexOf);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return extension;
	}

	// 通过Jsoup获取网页的单个图片地址_通过传入网页地址和生成图片目录
	// 目标网址为http://www.nipic.com/photo/jingguan/shanshui/index.html?page=1
	public static boolean getOnePic(String webURL, String picDestURL) {
		boolean flag = true;
		try {
			// webURL="http://www.nipic.com/photo/jingguan/shanshui/index.html?page="
			// 后面的数字逐个加1 直到2010
			// 创建Document对象,拿到元素对象再操作属性。
			File file = new File(picDestURL);
			if (!file.exists()) {
				file.mkdir();
			}
			int count = 2220;
			for (int i = 112; i <= 2010; i++) {
				// 分2010次拿到每页的网址
				try {
					String mainURL = webURL + i;
					Document doc = Jsoup.connect(mainURL).get();
					// 拿到每个页面的每个class元素
					Elements elements = doc.getElementsByClass("relative block works-detail hover-none works-img-box");
					for (Element element : elements) {
						try {
							// 获取每个页面的大图的网址
							String picHrefUrl = element.attr("href");
							// 获取每个大图的详细地址
							String picURL = getPicURL(picHrefUrl);
							// 从图片的详细地址开始下载单个图片到本地目标路径
							downloadPicToLocal(picURL, picDestURL + "\\" + (++count) + getNameExtension(picURL));
							System.out.println("已抓取" + count + "张图片。");
						} catch (Exception e) {
							// TODO: handle exception
						}

					}
				} catch (Exception e) {
					// TODO: handle exception
				}

			}
			// 计数器归零
			count = 0;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			flag = false;
			new RuntimeException("在服务器找不到对应图片,正在寻找下一个图片中。。。");
		}
		return flag;
	}

	public static void main(String[] args) {
		boolean result = getOnePic("http://www.nipic.com/photo/jingguan/shanshui/index.html?page=",
				"G:\\PictureSpider");
		System.out.println(result);

	}
}

代码运行效果如下:






所有图片都能打开。。。








  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值