爬虫
拆分过程
请求,过滤(提取),存储
爬虫的请求
maven 依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>get请求
public static void main(String[] args) {
CloseableHttpClient client = HttpClients.createDefault(); //创建httpclient 对象。
HttpGet httpGet = new HttpGet("https://java.ffffffff0x.com/api"); //创建get请求对象。
CloseableHttpResponse response = null;
try {
response = client.execute(httpGet); //发送get请求
if (response.getStatusLine().getStatusCode()==200){
String s = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(s);
System.out.println(httpGet);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
response.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}get携带参数请求
post请求
在 get 和 post 的请求不携带参数请求当中,get 的请求方式和 post 的请求方式基本类似。但是创建请求对象时,get 请求用的是 HttpGet 来生成对象,而 Post 则是 HttpPost 来生成对象。
post携带参数请求
走代理
连接池
如果每次请求都要创建 HttpClient,会有频繁创建和销毁的问题,可以使用连接池来解决这个问题。
创建一个连接池对象:
创建连接池代码
HttpClient 请求配置
爬虫的提取
jsoup
jsoup 是一款 Java 的 HTML 解析器,可直接解析某个 URL 地址、HTML 文本内容。它提供了一套非常省力的 API,可通过 DOM,CSS 以及类似于 jQuery 的操作方法来取出和操作数据。
jsoup 的主要功能如下:
从一个 URL,文件或字符串中解析 HTML;
使用 DOM 或 CSS 选择器来查找、取出数据;
可操作 HTML 元素、属性、文本;
maven 依赖
来一段爬取论坛 title 的代码
这里的 first() 代表获取第一个元素,text() 表示获取标签内容
dom遍历元素
爬取文章
多线程爬取
爬虫类
主类
这里执行会访问 50 次 https://www.freebuf.com/articles/network/274294.html , 然后就被 freebuf 封 ip 了😂
Source & Reference
https://www.cnblogs.com/nice0e3/p/13488064.html
https://blog.csdn.net/ly6cyh/article/details/77141346
https://www.cnblogs.com/nice0e3/p/13488064.html