使用 Nodejs 从豆瓣小组中爬取帖子,并进行过滤。
前端网页解析
网页结构
打开一个豆瓣小组网页,例如
https://www.douban.com/group/16473/
使用 F12 解析网站,可以看到,每一个帖子都由一个a
标签构成,标题为title
我们需要提取的包括标题
、URL
以及时间
信息,因此可以直接使用request
以及cheerio
包进行提取:
request(opt, function (error, response, body) {
if (error) {
return cb(error);
}
var $ = cheerio.load(body, {
normalizeWhitespace: true,
decodeEntities : false
});
var items = [];
$('.olt tr').slice(1).each(function (index, el) {
var title = $('.title > a', el).attr('title');
if (checkIncludeWords(title, includeWords) && checkExcludeWords(title, excludeWords)) {
var item = {
title : title,
href : $('.title > a', el).attr('href'),
lastTime: $('.time', el).text()
};
console.log('fetch item', item);
items.push(item);
}
});
发送请求
注意,直接发送 request 请求,会出现 403 错误,因此我们需要伪造报文头部,这里伪造的是 Mac 电脑上的 Chrome(也就是我电脑上的配置):
/**
* 请求参数初始化
* @param: urls:请求的url、 opts:请求header参数, num:爬取的页数
*/