nodeJs知多少之爬虫技术点

发表于:2021-9-27 09:18

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:紫日残月    来源:掘金

#
爬虫
分享:
  背景
  最近打算把之前看过的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;

  本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号