人工智能现场

node.js 使用superagent与cheerio写爬虫,福利贴

前言

对于我这样普通程序员来说,想获取可观的免费数据,最直接的办法就是爬虫了。正好刚学node.js不久,写一个简单的爬虫练练手。废话不多说,直奔主题。

正文

目标

这次要爬的是煎蛋网,找出妹子图2016年度最受欢迎的(oo数量最多的)十张图片。

用到的模块

SuperAgent – 用此来获得网页信息
cheerio – nodejs版的JQuery

具体流程

编写代码前,先打开Chrome分析一下页面源代码 https://i.jandan.net/ooxx/

现在开始写我们的程序,创建一个文件夹,进去之后
npm init ,填上基本信息之后
npm install superagent cheerio --save
新建一个app.js,就可以编写我们的代码逻辑了。
查看全部代码 github

核心代码

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
var topten = [{ author : '', date : '',year:'', oo : 0, xx: 0 , url:''}]//需要获取的数据结构
var page = 2300 //从2300页开始爬
var bcontinue = true
getSeeds = function(url){
superagent.get('http://i.jandan.net/ooxx/page-'+url)
.end(function(err,docs){ //通过superagent获取网页数据
page--
if(!err){
console.log(page)
var $ = cheerio.load(docs.text) //使用cheerio解析数据
$('.commentlist li').each(function(){
var json = { author:'', year:'', date:'', oo:0, xx:0, url:''};
var data = $(this);
json.date = data.children().eq(1).text()
json.year = json.date.substring(2, 6)
if(json.year == '2016'){ //存储2016年的妹子图
json.oo = parseInt(data.find("*[id*='cos_support']").text())
json.author = data.children().first().text()
json.xx = parseInt(data.find("*[id*='cos_unsupport']").text())
json.url = data.find('.commenttext p img').attr('src')
var lastone = topten[topten.length-1] //只保存oo次数最多的十张图
if(lastone.oo < json.oo){
topten.push(json)
topten.sort(function(a, b) { return b.oo - a.oo });
if(topten.length>10){
topten.pop()
}
}
}
if(json.year == '2015'){
bcontinue = false
}
})
}
if (bcontinue){
getSeeds(page)
}else{
console.log(topten)
}
})
};

爬到的结果

1
2
3
4
5
6
7
8
9
10
11
12
[ { author: 'Kill',
year: '2016',
date: '@ 2016-09-20 17:47:07',
oo: 1949,
xx: 53,
url: '//ww3.sinaimg.cn/thumb180/0064r0Mujw1f1sb5tt0aug30b4068x6p.gif' },
{ author: 'wjking512',
year: '2016',
date: '@ 2016-12-27 02:59:24',
oo: 1815,
xx: 75,
url: '//ww1.sinaimg.cn/mw600/9b17754bjw1e534athnt4j20m80kgtd1.jpg' },...

说好的福利

前三名

坚持原创技术分享,您的支持将鼓励我继续创作!