-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
64 lines (58 loc) · 2.09 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
var fs = require('fs');
var http = require('http');
var cheerio = require('cheerio');
var eventproxy = require('eventproxy');
var superagent = require('superagent');
var meizhiUrl = 'http://meizhi.im';
superagent.get(meizhiUrl)
.set('User-Agent', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0')
.end(function (err, res) {
if (err) throw err;
var topicUrls = [];
var $ = cheerio.load(res.text);
$('.box > a').each(function (i, element) {
var href = meizhiUrl + $(this).attr('href');
topicUrls.push(href);
});
var ep = new eventproxy();
ep.after('topic_html', topicUrls.length, function (topics) {
var imgUrls = [];
topics.forEach(function (topic) {
var $ = cheerio.load(topic);
$('.show-box img').each(function (i, element) {
var src = $(this).attr('src');
imgUrls.push(src);
});
});
imgUrls.forEach(function (imgUrl) {
http.get(imgUrl, function (res) {
res.setEncoding('binary');
var imageData = '';
res.on('data', function (data) {
imageData += data;
}).on('end', function () {
var imageName = res.headers['etag'];
var imageType = res.headers['content-type'];
var imageFullName = imageName.split('"')[1] + '.' + imageType.split('/')[1];
fs.writeFile('images/' + imageFullName, imageData, 'binary', function (err) {
if (err) throw err;
console.log('Image ' + imageFullName +' saved!');
});
});
});
});
});
topicUrls.forEach(function (topicUrl) {
superagent.get(topicUrl)
.set('User-Agent', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0')
.end(function (err, res) {
if (err) throw err;
if (res.statusCode == 200) {
console.log('Fetch ' + topicUrl + ' successful!');
ep.emit('topic_html', res.text);
} else {
console.log('Fetch ' + topicUrl + ' failed!');
}
});
});
});