大致流程:通过url获取到页面,解析页面元素,标签,获取到自己需要的内容,如图片的url,最后通过IO流将图片下载至本地!下图是 爬取成功的图片,请继续往下看 ↓ ↓ ↓。
依赖导入
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.3</version>
</dependency>
首先对网站页面 F12 进行解析,分析标签及元素。本文以壁纸网作为参考。
2.1根据class获取 元素 此时获取的是元素列表Elements 需要进行遍历 拿到单个Element,再进行解析。
2.2 对单个Element 进行解析 ,取到 img 标签, 并拿到 alt 作为图片名称和图片的远端地址。
根据地址下载图片到本地。(注意:本地下载地址要匹配,文件夹要提前创建好,本文没有自动创建文件夹,及文件夹不存在的判断)
完整代码
public static void main(String[] args) throws IOException {
String url = "https://www.hdbz.net/wallpaper/car/";
Document parse = Jsoup.parse(new URL(url), 1000 * 30);
Elements elements = parse.getElementsByClass("mt15 clearfix pic-auto pic-list").get(0).getElementsByTag("a");
for (Element element : elements) {
String text = element.getElementsByTag("a").attr("href");
String imgUrl = "https://www.hdbz.net" + text;
Document document = Jsoup.parse(new URL(imgUrl), 1000 * 20);
String lastUrl = document.getElementsByClass("preview-pic").get(0).getElementsByTag("img").attr("src");
String imageName = document.getElementsByClass("preview-pic").get(0).getElementsByTag("img").attr("alt");
String download = download(lastUrl, imageName);
System.out.println(download + " 下载已完成!");
}
}
//下载图片工具类
public static String download(String urlString, String name) {
InputStream is = null;
FileOutputStream os = null;
try {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
// 输入流
is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
String time = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss").format(new Date());
// 输出的文件流
// String filename = System.getProperty("os.name").toLowerCase().contains("win") ? System.getProperty("user.home") + "\\Desktop\\temp.jpg" : "/home/project/temp.jpg";
String filename = "F:\\catchImages\\plant\\" + name + ".jpg";
File file = new File(filename);
os = new FileOutputStream(file, true);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
return filename;
} catch (Exception e) {
e.printStackTrace();
} finally {
// 完毕,关闭所有链接
try {
if (null != os) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}