forked from iNuanfeng/node-spider
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
326 lines (289 loc) · 8.7 KB
/
app.js
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
var express = require('express'),
app = express(),
request = require('request'),
iconv = require('iconv-lite'),
cheerio = require('cheerio'),
async = require("async"), // 控制并发数,防止被封IP
fs = require('fs'),
JSONStream = require('JSONStream'),
path = require('path');
var fetchData = []; // 存放爬取数据
var SaveToMongo = require('save-to-mongo');//用于将爬取的数据存储到MongoDB数据库
var Highcharts = require('highcharts');//将爬取的数据用Highchart展示
require('highcharts/modules/exporting')(Highcharts);//在Highcharts加载之后加载功能模块
/**
* 睡眠模拟函数
* @param {Number} numberMillis 毫秒
*/
function sleep(numberMillis) {
var now = new Date();
var exitTime = now.getTime() + numberMillis;
while (true) {
now = new Date();
if (now.getTime() > exitTime)
return;
}
}
/**
* 爬取品牌 & 车系
*/
function fetchBrand(req, res) {
var pageUrls = []; // 存放爬取网址
var count = 0; // 总数
var countSuccess = 0; // 成功数
var chars = ['A', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y', 'Z'];
for (var char of chars) {
count++;
pageUrls.push('http://www.autohome.com.cn/grade/carhtml/' + char + '.html');
}
var curCount = 0;
var reptileMove = function (url, callback) {
var startTime = Date.now(); // 记录该次爬取的开始时间
request({
url: url,
encoding: null // 关键代码
}, function (err, res, body) {
if (err || res.statusCode != 200) {
console.error(err);
console.log('抓取该页面失败,重新抓取该页面..')
reptileMove(series, callback);
return false;
}
var html = iconv.decode(body, 'gb2312')
var $ = cheerio.load(html);
var curBrands = $('dl');
for (var i = 0; i < curBrands.length; i++) {
var obj = {
name: curBrands.eq(i).find('dt div a').text(),
sub: []
}
fetchData.push(obj);
var curSeries = curBrands.eq(i).find('h4 a');
for (var j = 0; j < curSeries.length; j++) {
var obj = {
name: curSeries.eq(j).text(),
sub: [],
url: curSeries.eq(j).attr('href')
}
fetchData[fetchData.length - 1].sub.push(obj);
}
}
countSuccess++;
var time = Date.now() - startTime;
console.log(countSuccess + ', ' + url + ', 耗时 ' + time + 'ms');
callback(null, url + 'Call back content');
});
};
// 使用async控制异步抓取
// mapLimit(arr, limit, iterator, [callback])
// 异步回调
async.mapLimit(pageUrls, 1, function (url, callback) {
reptileMove(url, callback);
}, function (err, result) {
console.log('----------------------------');
console.log('品牌车系抓取完毕!');
console.log('----------------------------');
fetchYear(req, res);
});
}
/**
* 爬取年份
*/
function fetchYear(req, res) {
var count = 0; // 总数
var countSuccess = 0; // 成功数
var seriesArr = [];
// 轮询所有车系
for (var brand of fetchData) {
for (var series of brand.sub) {
count++;
seriesArr.push(series);
}
}
var curCount = 0;
var reptileMove = function (series, callback) {
var startTime = Date.now(); // 记录该次爬取的开始时间
curCount++; // 并发数
request({
url: series.url,
encoding: null // gbk转码关键代码
}, function (err, res, body) {
if (err || res.statusCode != 200) {
console.error(err);
console.log('抓取该页面失败,重新抓取该页面..')
reptileMove(series, callback);
return false;
}
var html = iconv.decode(body, 'gb2312')
var $ = cheerio.load(html);
// 页面默认的数据
var itemList = $('.interval01-list li');
itemList.each(function () {
var year = $(this).find('a').eq(0).text().substr(0, 4);
var name = $(this).find('a').eq(0).text();
var flag = false;
for (item of series.sub) {
if (item.name == year) {
item.sub.push(name);
flag = true;
}
}
if (!flag) {
var obj = {
name: year,
sub: [$(this).find('a').eq(0).text()],
url: ''
};
series.sub.push(obj);
}
});
// 下拉框中的年份抓取
var curYears = $('.cartype-sale-list li');
curYears.each(function () {
var year = $(this).text().substr(0, 4);
var flag = false;
var href = series.url;
var s = href.split('/')[3]; // 从url中截取所需的s参数
var y = ($(this).find('a').attr('data'))
var url = 'http://www.autohome.com.cn/ashx/series_allspec.ashx?s='
+ s + '&y=' + y;
for (item of series.sub) {
if (item.name == year) {
item.url = url;
flag = true;
}
}
if (!flag) {
var obj = {
name: year,
sub: [],
url: url
};
series.sub.push(obj);
}
})
curCount--;
countSuccess++;
var time = Date.now() - startTime;
console.log(countSuccess + ', ' + series.url + ', 耗时 ' + time + 'ms');
sleep(50);
callback(null, series.url + 'Call back content');
});
};
console.log('车系数据总共:' + count + '条,开始抓取...')
// 使用async控制异步抓取
// mapLimit(arr, limit, iterator, [callback])
// 异步回调
async.mapLimit(seriesArr, 10, function (series, callback) {
reptileMove(series, callback);
}, function (err, result) {
// 访问完成的回调函数
console.log('----------------------------');
console.log('车系抓取成功,共有数据:' + countSuccess);
console.log('----------------------------');
fetchName(req, res);
});
}
/**
* 爬取型号
*/
function fetchName(req, res) {
var count = 0; // 总数
var countSuccess = 0; // 成功数
var yearArr = [];
// 轮询所有车系
for (var brand of fetchData) {
for (var series of brand.sub) {
for (var year of series.sub) {
if (year.url) {
count++; // 过滤没有url的年款
yearArr.push(year);
}
}
}
}
var curCount = 0;
var reptileMove = function (year, callback) {
var startTime = Date.now(); // 记录该次爬取的开始时间
curCount++; // 并发数
// console.log(curCount + ': ' + series.url);
request({
url: year.url,
encoding: null // gbk转码关键代码
}, function (err, res, body) {
if (err || res.statusCode != 200) {
console.error(err);
console.log('抓取该页面失败,重新抓取该页面..')
console.log(year)
reptileMove(year, callback);
return false;
}
console.log(countSuccess + ', 抓取: ' + year.url)
var html = iconv.decode(body, 'gb2312')
try {
var data = JSON.parse(html)
} catch (e) {
console.log('error... 忽略该页面');
// reptileMove(series, callback);
curCount--;
callback(null, year.url + 'Call back content');
return false;
}
var specArr = data.Spec;
for (var item of specArr) {
year.sub.push(item.Name);
}
curCount--;
countSuccess++;
var time = Date.now() - startTime;
// sleep(100);
callback(null, year.url + 'Call back content');
});
};
console.log('车型数据总共:' + count + '条,开始抓取...')
// 使用async控制异步抓取
// mapLimit(arr, limit, iterator, [callback])
// 异步回调
async.mapLimit(yearArr, 20, function (year, callback) {
reptileMove(year, callback);
}, function (err, result) {
// 访问完成的回调函数
console.log('----------------------------');
console.log('车型抓取成功,共有数据:' + countSuccess);
console.log('----------------------------');
// res.send(fetchData);
var t = JSON.stringify(fetchData);
fs.writeFileSync('data.json', t);
//将data.json存入MongoDB中
fs.createReadStream(path.join(__dirname, './data.json'))
.pipe(JSONStream.parse('*'))
.pipe(saveToMongo)
.on('execute-error', function(err) {
console.log(err);
})
.on('done', function() {
console.log('存入完毕!');
process.exit(0);
});
});
}
/**
* 爬虫入口
*/
fetchBrand();
/**
* 配置MongoDB成功
*/
var saveToMongo = SaveToMongo({
uri: 'mongodb://127.0.0.1:27017/carDb', //mongoDB的地址
collection: 'savetomongo',
bulk: {
mode: 'unordered'
}
});
/**
* 创建图表
*/
Highcharts.chart('container', {
// Highcharts配置
});