Java爬虫学习
从今天开始学习Python,发现Python能做很多事情,比如深度学习训练模型,爬虫等等,然后很好奇Java有没有这种功能,就上网看了一下,发现真的有Java爬虫,了解了一下,随笔记一下
Java爬虫简介
java爬虫的相关工具是来源于Jsoup这个工具包
首先我们要知道:jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据。
package com.zukxu;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;
/**
* @author zukxu
* @description
* @date 2020-08-11 19:18
*/
public class Demo {
public static void main(String[] args) {
String url = "https://list.jd.com/list.html?cat=670%2C677%2C688&go=0";
try {
Connection connect = Jsoup.connect(url);
Document document = connect.get();
Elements elementsByClass = document.getElementsByClass("p-img");
for (Element byClass : elementsByClass) {
Elements img = byClass.getElementsByTag("img");
for (Element element : img) {
String src = "";
src = element.attr("source-data-lazy-img");
if (StringUtil.isBlank(src)) {
src = element.attr("data-lazy-img");
}
if (StringUtil.isBlank(src)) {
src = element.attr("src");
URL url1 = new URL("http:" + src);
URLConnection urlConnection = url1.openConnection();
System.out.println(src);
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream outputStream = new FileOutputStream("D:/Pictures/Camera Roll" + new Random().nextInt()+".jpg");
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
outputStream.close();
inputStream.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
上面的代码将进洞电脑的图片爬下来存放到文件夹中,但是要知道,只有页面上有html元素有的情况下,才能通过jsoup来爬虫,如果是通过接口获得的数据,那么通过jsoup是无法获取到的。只能通过其他工具才能获取到