JAVA爬虫
HttpClient
HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
使用 HttpClient 的 6 个步骤
1. 创建 HttpClient 的实例
2. 创建某种连接方法的实例,选择get或post请求
3. 确定是否有参数
4. 执行请求,并获得 response响应,然后获得HttpEntity对象
5. 释放连接。无论执行方法是否成功,都必须释放连接
6. 对得到后的内容进行处理
Pom.xml添加依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
GET请求
不带参
public static void main(String[] args) {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建HttpGet对象,设置url
HttpGet httpGet =new HttpGet("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#auto/zh/");
System.out.println("发起请求信息:"+httpGet);
CloseableHttpResponse response = null;
try {
//创建HttpClient发起请求,获取response
response = httpClient.execute(httpGet);
//解析响应
if (response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content);
}
}catch (IOException e){
e.printStackTrace();
}finally {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
带参
public static void main(String[] args) throws Exception {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置带参的url地址http://yun.itheima.com/search?keys=java
URIBuilder uriBuilder =new URIBuilder("http://yun.itheima.com/search");
uriBuilder.setParameter("keys","java");
//创建HttpGet对象,设置url
HttpGet httpGet =new HttpGet(uriBuilder.build());
System.out.println("发起请求信息:"+httpGet);
CloseableHttpResponse response = null;
try {
//创建HttpClient发起请求,获取response
response = httpClient.execute(httpGet);
//解析响应
if (response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content);
}
}catch (IOException e){
e.printStackTrace();
}finally {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
POST请求
不带参
public static void main(String[] args) {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建httpPost对象,设置url
HttpPost httpPost = new HttpPost("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#auto/zh/");
System.out.println("发起请求信息:"+httpPost);
CloseableHttpResponse response = null;
try {
//创建HttpClient发起请求,获取response
response = httpClient.execute(httpPost);
//解析响应
if (response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content);
}
}catch (IOException e){
e.printStackTrace();
}finally {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
带参
public static void main(String[] args) throws UnsupportedEncodingException {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建httpPost对象,设置url
HttpPost httpPost = new HttpPost("http://yun.itheima.com/search");
System.out.println("发起请求信息:"+httpPost);
//声明list集合,封装表单中的参数
List<NameValuePair> params =new ArrayList<NameValuePair>();
//设置带参的url地址http://yun.itheima.com/search?keys=java
params.add(new BasicNameValuePair("keys","java"));
//创建表单的Entity对象
UrlEncodedFormEntity formEntity =new UrlEncodedFormEntity(params,"utf8");
//设置表单的Entity对象到Post请求中
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
//创建HttpClient发起请求,获取response
response = httpClient.execute(httpPost);
//解析响应
if (response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content);
}
}catch (IOException e){
e.printStackTrace();
}finally {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
连接池
public static void main(String[] args) {
PoolingHttpClientConnectionManager cm =new PoolingHttpClientConnectionManager();
//设置连接数
cm.setMaxTotal(100);
//设置没个主机的最大连接数
cm.setDefaultMaxPerRoute(10);
doGet(cm);
}
private static void doGet(PoolingHttpClientConnectionManager cm) {
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
HttpGet httpGet =new HttpGet("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#auto/zh/");
CloseableHttpResponse response =null;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content.length());
}
}catch (IOException e){
e.printStackTrace();
}finally {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
连接请求配置
配置请求信息
//setConnectTimeout创建连接的最长时间,毫秒 、setConnectionRequestTimeout获取连接的最长
时间,毫秒
RequestConfig config =RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000).build();
httpGet.setConfig(config);
Jsoup解析
Jsoup是一款Java的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的AP,可通过DOM,CSs以及类似于 Jquery的操作方法来取出和操作数据。
jsoup的主要功能如下:“1.从一个URL,文件或字符串中解析HTML;2.使用DOM或CSS选择器来查找、取出数据;3.可操作HTML元素、属性、I文木;
maven加入依赖
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
Jsoup解析Url
@Test
public void JUrl()throws Exception{
//解析url地址,参数1:要访问的url,参数2:访问超时时间
Document doc = Jsoup.parse(new URL("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#zh/en/"), 100000);
//使用标签选择器
String text = doc.getElementsByTag("title").first().text();
System.out.println(text);
}
Jsoup解析文件
//解析文件
Document doc = Jsoup.parse(new File("F:\\front\\code\\vue01\\比较数字大小.html"),"utf8");
String text = doc.getElementsByTag("title").first().text();
System.out.println(text);
Dom方式获取元素
元素获取
1.根据d查询元素 getElementByld
2.根据标签获取元素 getElementsByTag
3.根据 class i获取元素 getElementsByClass
4.根据属性获取元素 getElementsByAttribute
@Test
public void DOMGet()throws Exception{
//解析文件
Document doc = Jsoup.parse(new File("F:\\front\\code\\vue01\\dom与diff算法.html"),"utf8");
//1.根据d查询元素 getElementById
Element elementById = doc.getElementById("101");
System.out.println("获取到文件内容:"+elementById.text());
//2.根据标签获取元素 getElementsByTag
Element th = doc.getElementsByTag("th").first();
System.out.println("获取到文件内容:"+th.text());
//3.根据 class i获取元素 getElementsByClass
Elements abc = doc.getElementsByClass("abc");
System.out.println("获取到文件内容:"+abc.text());
//4.根据属性获取元素 getElementsByAttribute
Elements id = doc.getElementsByAttribute("id");
System.out.println(id.text());
Elements id1 = doc.getElementsByAttributeValue("id", "101");
System.out.println(id1.text());
}