当前位置: 移动技术网 > IT编程>开发语言>JavaScript > nodeJs爬虫的技术点总结

nodeJs爬虫的技术点总结

2018年05月19日  | 移动技术网IT编程  | 我要评论

背景

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

依赖

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

日志配置

话不多说,直接上代码:

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()等函数添加日志信息就可以,会按天生成日志。相关信息网络上一堆。

爬取内容并处理

 superagent.get(cityitemurl).end((err, res) => {
  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来代理事件,处理一次资源处罚一次事件,所有事件触发完成后处理数据。

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

读写本地文件

创建文件夹

function mkdirsync(dirname) {
 if (fs.existssync(dirname)) {
  return true;
 }
 if (mkdirsync(path.dirname(dirname))) {
  fs.mkdirsync(dirname);
  return true;
 }

 return false;
}

读写文件

   const content = json.parse(fs.readfilesync(path.join(__dirname, './dir.json')));

   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 = require('bagpipe');

const bagpipe = new bagpipe(10);

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

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

function downloadimage(src, dest, callback) {
 request.head(src, (err, res, body) => {
  if (src && src.indexof('http') > -1 || src.indexof('https') > -1) {
   request(src).pipe(fs.createwritestream(dest)).on('close', () => {
    callback(null, dest);
   });
  }
 });
}

编码

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

const $ = cheerio.load(buf, { decodeentities: false });

来禁止编码,

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

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

const reg = /<.*?>/g;

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网