Java爬虫技术
使用爬虫技术最常见的API是httpclient和jsoup,当然jdk还有自带的爬虫API;下面介绍下两者的区别:
①HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议((GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等))的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
HttpClient的主要功能:
1、实现了所有 HTTP 的方法
2、支持 HTTPS 协议
3、支持代理服务器(Nginx等)等
4、支持自动(跳转)转向②jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据。
主要功能
从一个URL,文件或字符串中解析HTML使用DOM或CSS选择器来查找、取出数据使用DOM或CSS选择器来查找、取出数据可操作HTML元素、属性、文本可操作HTML元素、属性、文本。总而言之,使用httpclient进行网络爬虫获取到的数据无法进行解析,而jsoup自带解析器,能够更加方便的获取想要的数据。
上手实践:
使用Java中jdk自带的API
public class JDKTest {
@Test
public void testGet() throws Exception {
// 1、 确定要爬取的URL
URL url = new URL("https://www.baidu.com");
//2、 获取连接对象
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//3、 设置连接信息
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0");
// 4、获取数据
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
String html="";
while((line=bufferedReader.readLine())!=null){
html+=line+"\n";
}
System.out.println(html);
// 5、关闭资源
inputStream.close();
bufferedReader.close();
}
}
导入相关依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
HttpClient 的使用
public class HttpClientTest {
@Test
public void test() throws IOException {
//1、创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2、创建httpget请求并设置
HttpGet httpGet = new HttpGet("https://www.baidu.com");
// 请求头信息,可从浏览器中获取,按F12便可查找到
httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0");
//3、发起请求
CloseableHttpResponse response = httpClient.execute(httpGet);
//4、获取响应码和状态码数据
if(response.getStatusLine().getStatusCode()==200){
String string = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(string);
}
//5、关闭数据
httpClient.close();
}
}
jsoup的使用:
这里使用jsoup获取腾讯王者荣耀皮肤,获取到的是网址地址。
public class JsoupTest {
@Test
public void test() throws IOException {
// connect里面的网址是王者荣耀官网皮肤网址
Document document = Jsoup.connect("https://pvp.qq.com/web201605/herolist.shtml").get();
String title = document.getElementsByTag("title").first().text();
Elements select = document.select(".herolist-content > ul > li > a >img");
Elements src = document.getElementsByAttribute("src");
System.out.println( src);
}
访问上面标红的网址,如下:
当然我们也可以使用连接池创建,关注我下期带你使用连接池。