-
博客
-
学院
-
下载
-
GitChat
-
TinyMind
-
论坛
-
APP
-
问答
-
商城
-
VIP会员
-
活动
-
招聘
-
ITeye
-
-
-
写博客
-
发Chat
-
传资源
-
登录注册
原
Java爬虫(二)– httpClient模拟Http请求+jsoup页面解析
2018年03月01日 15:00:12 阅读数:393 标签: java爬虫httpClientjsoup 更多
个人分类: java开发笔记
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/coqcnbkggnscf062/article/details/79412587
前言
在了解了爬虫的大概原理和目前的技术现状之后,我就开始了java爬虫的蹒跚之旅。
首先我想到的是用框架,了解到的主流的Nutch、webmagic、webcollector等等,都看了一遍,最好懂的是webmagic,因为是国人开发的,有中文文档,看的很舒服。刚开始写练手的demo之后发现都很舒服,设置好对应爬取规则、爬取深度之后,就能得到想要的数据。
但是当我正式准备开发的时候,很快就发现我的业务场景并不适用于这些框架(Emm..当然也有可能是我太菜了)。
为什么这么说呢,让我们先回到上篇中我摘录的爬虫原理,传统爬虫从一个或若干初始网页的URL开始,获得初始网页上的URL,在抓取网页的过程中,不断从当前页面上抽取新的URL放入队列,直到满足系统的一定停止条件。
也就是,目标数据所在的网页的url都是在上一层页面上可以抽取到的,对应到页面上具体的讲法就是,这些链接都是写在html 标签的 href 属性中的,所以可以直接抽取到。
那些demo中被当做抓取对象的网站一般是douban、baidu、zhihu之类的数据很大的公开网站,url都是写在页面上的,而我的目标网站时险企开放给代理公司的网站,具有不公开、私密的性质,一个页面转到下一个页面的请求一般都是通过js动态生成url发起的,并且很多是post请求。
虽然那些框架有很多优越诱人的特性和功能,本着先满足需求,在进行优化的原则,我准备先用比较底层的工具一步步的模拟这些http请求。
正好,我发现webmagic底层模拟请求的工具用的就是Apache HttpClient,所以就用这个工具来模拟了。
HttpClient
HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包。它相比传统的 HttpURLConnection,增加了易用性和灵活性,它不仅让客户端发送 HTTP 请求变得更容易,而且也方便了开发人员测试接口(基于 HTTP 协议的),即提高了开发的效率,也方便提高代码的健壮性
在搜索相关资料的时候,会发现网上有两种HttpClient。
org.apache.commons.httpclient.HttpClient与org.apache.http.client.HttpClient的区别:Commons的HttpClient项目现在是生命的尽头,不再被开发,已被Apache HttpComponents项目HttpClient和的HttpCore模组取代,提供更好的性能和更大的灵活性
实战
HTTP GET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 1
2 public static String sendGet(String url) {
3 CloseableHttpClient httpclient = HttpClients.createDefault();
4 CloseableHttpResponse response = null;
5 String content = null;
6 try {
7 HttpGet get = new HttpGet(url);
8 response = httpClient.execute(httpGet);
9 HttpEntity entity = response.getEntity();
10 content = EntityUtils.toString(entity);
11 EntityUtils.consume(entity);
12 return content;
13 } catch (Exception e) {
14 e.printStackTrace();
15 if (response != null) {
16 try {
17 response.close();
18 } catch (IOException e1) {
19 e1.printStackTrace();
20 }
21 }
22 }
23 return content;
24 }
25
-
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
1
2
3
4
5
6
7
8
9 1URI uri = new URIBuilder()
2 .setScheme("http")
3 .setHost("www.test.com")
4 .setPath("/test")
5 .setParameter("msg", "hello")
6 .setParameter("type", "test")
7 .build();
8HttpGet httpget = new HttpGet(uri);
9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
HTTP POST
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 1 // application/x-www-form-urlencoded
2 public static String sendPost(HttpPost post, List<NameValuePair> nvps) {
3 CloseableHttpClient httpclient = HttpClients.createDefault();
4 CloseableHttpResponse response = null;
5 String content = null;
6 try {
7 // nvps是包装请求参数的list
8 if (nvps != null) {
9 post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
10 }
11 // 执行请求用execute方法,content用来帮我们附带上额外信息
12 response = httpClient.execute(post);
13 // 得到相应实体、包括响应头以及相应内容
14 HttpEntity entity = response.getEntity();
15 // 得到response的内容
16 content = EntityUtils.toString(entity);
17 EntityUtils.consume(entity);
18 return content;
19 } catch (Exception e) {
20 e.printStackTrace();
21 } finally {
22 if (response != null) {
23 try {
24 response.close();
25 } catch (IOException e) {
26 e.printStackTrace();
27 }
28 }
29 }
30 return content;
31 }
32
33 // application/json
34 public static String sendPostJson (String url, JSONObject object) {
35 HttpPost httpPost = new HttpPost(url);
36 CloseableHttpClient httpclient = HttpClients.createDefault();
37 try {
38 // json方式
39 StringEntity entity = new StringEntity(object.toString(),"utf-8");//解决中文乱码问题
40 entity.setContentEncoding("UTF-8");
41 entity.setContentType("application/json;charset=UTF-8");
42 httpPost.setEntity(entity);
43 HttpResponse resp = httpClient.execute(httpPost);
44 if(resp.getStatusLine().getStatusCode() == 200) {
45 HttpEntity he = resp.getEntity();
46 return EntityUtils.toString(he,"UTF-8");
47 }
48 } catch (IOException e) {
49 e.printStackTrace();
50 }
51 return null;
52 }
53
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
HttpEntiy接口
1
2
3
4
5
6
7
8
9
10
11
12
13 1CloseableHttpResponse response = httpclient.execute(request);
2HttpEntity entity = response.getEntity();
3if (entity != null) {
4 long length = entity.getContentLength();
5 if (length != -1 && length < 2048) {
6 String responseBody = EntityUtils.toString(entity);
7 }
8 else {
9 InputStream in = entity.getContent();
10 // read from the input stream ...
11 }
12}
13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
HTTP Header
1
2
3
4 1HttpPost post = new HttpPost(url);
2post.setHeader("Content-Type", "application/json;charset=UTF-8");
3post.setHeader("Host", "www.test.com.cn");
4
-
1
-
2
-
3
1
2
3
4
5
6
7
8
9
10 1HttpResponse resp = httpClient.execute(···);
2// 读取指定header的第一个值
3resp.getFirstHeader(headerName).getValue();
4// 读取指定header的最后一个值
5resp.getLastHeader(headerName).getValue();
6// 读取指定header
7resp.getHeaders(headerName);
8// 读取所有的header
9resp.getAllHeaders();
10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
页面解析
jsoup
1
2
3
4
5
6 1String page = "..."; // 假设这是csdn页面的html
2Document doc = Jsoup.parse(page); //得到document对象
3Element feedlist = doc.select("#feedlist_id").get(0); // 获取父级元素
4String title = feedlist.select("a").get(0).text(); // 获取第一个a标签的内容
5// 如果是input之类的标签,取value值就是用val()方法
6
-
1
-
2
-
3
-
4
-
5
1
2
3
4
5
6
7
8
9
10
11 1// 通过Class属性来定位元素,获取的是所有带这个class属性的集合
2getElementsByClass()
3// 通过标签名字来定位元素,获取的是所有带有这个标签名字的元素结合
4getElementsByTag();
5// 通过标签的ID来定位元素,这个是精准定位,因为页面的ID基本不会重复
6getElementById();
7// 通过属性和属性名来定位元素,获取的也是一个满足条件的集合;
8getElementsByAttributeValue();
9// 通过正则匹配属性
10getElementsByAttributeValueMatching()
11
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
正则表达式
1
2
3
4
5
6
7
8 1 Matcher matcher;
2 String page; = "..."; // 页面html
3 String regex = "..."; // 正则表达式
4 matcher = Pattern.compile(regex).matcher(page);
5 if (matcher.find())
6 // 子询价单号
7 String rst = matcher.group(1);
8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
个人资料
最新文章
- Java爬虫(八)– httpClient进阶:HTTPS和证书认证(原理总结篇)
- Java爬虫(七)- httpClient进阶: https 和 证书认证(讲故事篇)
- 【开发笔记】ajax交互报错调试,请求失败状态码为0时的解析,附解决方案
- Java爬虫(六)– httpClient进阶:超时时间设置+cookie保存策略
- Java爬虫(五)– httpClient进阶:使用代理(详细解析)
个人分类
- java开发笔记10篇
归档
- 2018年4月3篇
- 2018年3月6篇
- 2018年2月1篇
热门文章
- Java爬虫(三)– httpClient 模拟登录 + cookie 登录状态管理
- 【开发笔记】spring + websocket 实现服务端推送消息(附几个坑)
- Java爬虫(四)– Java 调用 JS 函数 模拟页面 JS 密码加密(附几个知识点)
- Java爬虫(二)– httpClient模拟Http请求+jsoup页面解析
- Java爬虫(六)– httpClient进阶:超时时间设置+cookie保存策略
联系我们
-
「码字计划」:拿万元写作基金!
-
-
-
-
-
-