nodeJs爬虫的技术点总结

背景

最近打算把之前看过的nodeJs相关的内容在复习下,顺便写几个爬虫来打发无聊,在爬的过程中发现一些问题,记录下以便备忘。

依赖

用到的是在网上烂大街的cheerio库来处理爬取的内容,使用superagent处理请求,log4js来记录日志。

日志配置

话不多说,直接上代码

rush:js;"> const log4js = require('log4js');

log4js.configure({
appenders: {
cheese: {
type: 'dateFile',filename: 'cheese.log',pattern: '-yyyy-MM-dd.log',// 包含模型
alwaysIncludePattern: true,maxLogSize: 1024,backups: 3 }
},categories: { default: { appenders: ['cheese'],level: 'info' } }
});

const logger = log4js.getLogger('cheese');
logger.level = 'INFO';

module.exports = logger;

以上直接导出一个logger对象,在业务文件里直接调用logger.info()等函数添加日志信息就可以,会按天生成日志。相关信息网络上一堆。

爬取内容并处理

{ if (err) { return console.error(err); }

const $ = cheerio.load(res.text);
// 解析当前页面,获取当前页面的城市链接地址
const cityInfoEle = $('.newslist1 li a');
cityInfoEle.each((idx,element) => {
const $element = $(element);
const sceneURL = $element.attr('href'); // 页面地址
const sceneName = $element.attr('title'); // 城市名称
if (!sceneName) {
return;
}
logger.info(当前解析到的目的地是: ${sceneName},对应的地址为: ${sceneURL});

getDesInfos(sceneURL,sceneName); // 获取城市详细信息

ep.after('getDirInfoComplete',cityInfoEle.length,(dirInfos) => {
const content = JSON.parse(fs.readFileSync(path.join(__dirname,'./imgs.json')));

dirInfos.forEach((element) => {
 logger.info(`本条数据为:${JSON.stringify(element)}`);
 Object.assign(content,element);
});

fs.writeFileSync(path.join(__dirname,'./imgs.json'),JSON.stringify(content));

});
});
});

使用superagent请求页面,请求成功后使用cheerio 来加载页面内容,然后使用类似Jquery的匹配规则来查找目的资源。

多个资源加载完成,使用eventproxy来代理事件,处理一次资源处罚一次事件,所有事件触发完成后处理数据。

以上就是最基本的爬虫了,接下来就是一些可能会出问题或者需要特别注意的地方了。。。

读写本地文件

创建文件

rush:js;"> function mkdirsync(dirname) { if (fs.existsSync(dirname)) { return true; } if (mkdirsync(path.dirname(dirname))) { fs.mkdirsync(dirname); return true; }

return false;
}

读写文件

dirInfos.forEach((element) => {
logger.info(本条数据为:${JSON.stringify(element)});
Object.assign(content,element);
});

fs.writeFileSync(path.join(__dirname,'./dir.json'),JSON.stringify(content));

批量下载资源

下载资源可能包括图片、音频等等。

使用Bagpipe处理异步并发 参考

const bagpipe = new Bagpipe(10);

bagpipe.push(downloadImage,url,dstpath,(err,data) => {
if (err) {
console.log(err);
return;
}
console.log([${dstpath}]: ${data});
});

下载资源,使用stream来完成文件写入。

{ if (src && src.indexOf('http') > -1 || src.indexOf('https') > -1) { request(src).pipe(fs.createWriteStream(dest)).on('close',() => { callback(null,dest); }); } }); }

编码

有时候直接使用 cheerio.load处理的网页内容,写入文件后发现是编码后的文字,可以通过

rush:js;"> const $ = cheerio.load(buf,{ decodeEntities: false });

禁止编码,

ps: encoding库和iconv-lite未能实现将utf-8编码的字符转换为中文,可能是还对API不熟悉,稍后可以关注下。

最后,附上一个匹配所有dom标签的正则

rush:js;"> const reg = /<.*?>/g;

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...