Java爬虫实现爬取京东上的手机搜索页面 HttpCliient+Jsoup

2025-05-29 0 14

1、需求及配置

需求:爬取京东手机搜索页面的信息,记录各手机的名称,价格,评论数等,形成一个可用于实际分析的数据表格。

Java爬虫实现爬取京东上的手机搜索页面 HttpCliient+Jsoup

使用maven项目,log4j记录日志,日志仅导出到控制台。

maven依赖如下(pom.xml)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21
<dependencies>

<dependency>

<groupid>org.apache.httpcomponents</groupid>

<artifactid>httpclient</artifactid>

<version>4.5.3</version>

</dependency>

<dependency>

<!-- jsoup html parser library @ https://jsoup.org/ -->

<groupid>org.jsoup</groupid>

<artifactid>jsoup</artifactid>

<version>1.11.2</version>

</dependency>

<!-- https://mvnrepository.com/artifact/log4j/log4j -->

<dependency>

<groupid>log4j</groupid>

<artifactid>log4j</artifactid>

<version>1.2.17</version>

</dependency>

</dependencies>

log4j配置(log4j.properties),将info及以上等级信息输出到控制台,不单独设置输出文档。

?

1

2

3

4

5

6
log4j.rootlogger=info, console

#console

log4j.appender.console=org.apache.log4j.consoleappender

log4j.appender.console.layout=org.apache.log4j.patternlayout

log4j.appender.console.layout.conversionpattern=%d [%t] %-5p [%c] - %m%n

2、需求分析与代码

2.1需求分析

第一步,建立客户端与服务端的连接,并通过url获得网页上的html内容。

第二步,解析html内容,获取需要的元素。

第三步,将html内容输出到本地的文本文档中,可直接通过其他数据分析软件进行分析。

根据以上分析,建立4个类,gethtml(用于获取网站html), parsehtml(用于解析html), writeto(用于输出文档), maincontrol(主控).下面分别对四个类进行说明。为使代码尽量简洁,所有的异常均从方法上直接抛出,不catch。

2.2代码

2.2.1gethtml类

该类包含两个方法:geth(string url), urlcontrol(string baseurl, int page),分别用于获取网页html及控制url。由于此次爬取的网页内容只是京东上某一类商品的搜索结果,所以不需要对页面上所有的url进行遍历,只需要观察翻页时url的变化,推出规律即可。只向外暴露urlcontrol方法,类中设置一个private的log属性:private static logger log = logger.getlogger(gethtml.class); 用于记录日志。

geth(string url),对单个url的html内容进行获取。

urlcontrol(string baseurl, int page),设置循环,访问多个页面的数据。通过审查元素可以看到京东上搜索页page的变化实际是奇数顺序的变化。

Java爬虫实现爬取京东上的手机搜索页面 HttpCliient+Jsoup

再看一下点击后网址的变化,可以发现实际变化的是page属性的值。通过拼接的方式就可以很的容易的获得下一个网页的地址。

https://search.jd.com/search?keyword=%e6%89%8b%e6%9c%ba&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&cid2=653&cid3=655&page=3&s=47&click=0
https://search.jd.com/search?keyword=%e6%89%8b%e6%9c%ba&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&cid2=653&cid3=655&page=5&s=111&click=0
https://search.jd.com/search?keyword=%e6%89%8b%e6%9c%ba&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&cid2=653&cid3=655&page=7&s=162&click=0

整体代码:

?

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

54

55

56

57

58

59
import java.io.ioexception;

import org.apache.http.httpentity;

import org.apache.http.client.clientprotocolexception;

import org.apache.http.client.methods.closeablehttpresponse;

import org.apache.http.client.methods.httpget;

import org.apache.http.impl.client.closeablehttpclient;

import org.apache.http.impl.client.httpclients;

import org.apache.http.util.entityutils;

import org.apache.log4j.logger;

public class gethtml {

//建立日志

private static logger log = logger.getlogger(gethtml.class);

private static string geth(string url) throws clientprotocolexception, ioexception {

//控制台输出日志,这样每条访问的url都可以在控制台上看到访问情况

log.info("正在解析" + url);

/*

* 以下内容为httpclient建立连接的一般用法

* 使用httpclient建立客户端

* 使用get方法访问指定url

* 获得应答

* */

closeablehttpclient client = httpclients.createdefault();

httpget get = new httpget(url);

closeablehttpresponse response = client.execute(get);

/*

* 以下内容为将html内容转化为string

* 获得应答体

* 将应答体转为string格式,此处使用了entityutils中的tostring方法,编码格式设置为"utf-8"

* 完成后关闭客户端与应答

* */

httpentity entity = response.getentity();

string content;

if (entity != null) {

content = entityutils.tostring(entity, "utf-8");

client.close();

response.close();

return content;

} else

return null;

}

public static void urlcontrol(string baseurl, int page) throws clientprotocolexception, ioexception {

//设置当前页count

int count = 1;

//如果当前页小于想要爬取的页数则执行

while (count < page) {

//实际访问的url为不变的url值拼接上url变化的值

string u = baseurl + (2 * count - 1) + "&click=0";

//此处调用parsehtml类中的方法对url中的html页面进行处理,后面详细介绍该类

string content = parsehtml.parse(geth(u)).tostring();

//此处调用writeto类中的方法对解析出来的内容写入到本地,后面详细介绍该类

writeto.writeto(content);

count++;

}

}

}

2.2.2parsehtml类

该步骤需要通过审查元素对需要爬取内容的标签进行确定,再通过jsoup中的css选择器进行获取。

?

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
import org.jsoup.jsoup;

import org.jsoup.nodes.document;

import org.jsoup.nodes.element;

import org.jsoup.select.elements;

public class parsehtml {

public static stringbuilder parse(string content)

{

//使用jsoup中的parse方法对已经转换为string的html内容进行分析,返回值为document类

document doc = jsoup.parse(content);

//使用选择器select对需要找的元素进行抓取,例如第一个select中选择的是ul标签中class属性等于gl-warp clearfix的内容

elements ele = doc.select("ul[class = gl-warp clearfix]").select("li[class=gl-item]");

//设置一个容器,用于装各个属性

stringbuilder sb = new stringbuilder();

//通过上一个选择器可以获得整个页面中所有符合要求的元素,也即各款手机,下面则需要对每款手机进行遍历,获取其属性

for (element e : ele) {

//此处对各个属性的获取参考了网上一篇爬取京东上内容的文章,应该有其他不同的写法

string id = e.attr("data-pid");

string mingzi = e.select("div[class = p-name p-name-type-2]").select("a").select("em").text();

string jiage = e.select("div[class=p-price]").select("strong").select("i").text();

string pinglun = e.select("div[class=p-commit]").select("strong").select("a").text();

//向容器中添加属性

sb.append(id+"\\t");

sb.append(mingzi+"\\t");

sb.append(jiage+"\\t");

sb.append(pinglun+"\\t");

sb.append("\\r\\n");

}

return sb;

}

}

2.2.3writeto类

此类中的方法将解析完成的内容写入到一个本地文件中。只是简单的io。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16
import java.io.bufferedwriter;

import java.io.file;

import java.io.filewriter;

import java.io.ioexception;

public class writeto {

// 设置文件存放的位置

private static file f = new file("c:\\\\jingdong.txt");

public static void writeto(string content) throws ioexception {

//使用续写的方式,以免覆盖前面写入的内容

bufferedwriter bw = new bufferedwriter(new filewriter(f, true));

bw.append(content);

bw.flush();

bw.close();

}

}

2.2.4maincontrol类

主控程序,写入基地址与想要获取的页面数。调用gethtml类中的urlcontrol方法对页面进行抓取。

?

1

2

3

4

5

6

7

8

9

10

11

12
import java.io.ioexception;

import org.apache.http.client.clientprotocolexception;

public class maincontrol {

public static void main(string[] args) throws clientprotocolexception, ioexception {

// todo auto-generated method stub

string baseurl = "https://search.jd.com/search?keyword=%e6%89%8b%e6%9c%ba&enc="

+ "utf-8&qrst=1&rt=1&stop=1&vt=2&cid2=653&cid3=655&page=";

int page = 5;//设置爬取页数

gethtml.urlcontrol(baseurl, page);

}

}

3、爬取结果

爬取20页。

3.1控制台输出

Java爬虫实现爬取京东上的手机搜索页面 HttpCliient+Jsoup

3.2文档输出

可以直接使用excel打开,分隔符为制表符。列分别为商品编号,名称,价格与评论数。

Java爬虫实现爬取京东上的手机搜索页面 HttpCliient+Jsoup

4、小结

此次爬取使用了httpclient与jsoup,可以看到对于简单的需求,这些工具还是非常高效的。实际上也可以把所有类写到一个类当中,写多个类的方式思路比较清晰。

以上这篇java爬虫实现爬取京东上的手机搜索页面 httpcliient+jsoup就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

原文链接:http://www.cnblogs.com/pandasgb/archive/2017/11/30/7920323.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java爬虫实现爬取京东上的手机搜索页面 HttpCliient+Jsoup https://www.kuaiidc.com/113965.html

相关文章

发表评论
暂无评论