51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 2191|回复: 0

[转贴] nodeJs知多少之爬虫技术点

[复制链接]
  • TA的每日心情
    无聊
    昨天 09:11
  • 签到天数: 932 天

    连续签到: 4 天

    [LV.10]测试总司令

    发表于 2021-9-27 10:06:07 | 显示全部楼层 |阅读模式
     背景
      最近打算把之前看过的nodeJs相关的内容在复习下,顺便写几个爬虫来打发无聊,在爬的过程中发现一些问题,记录下以便备忘。
      依赖
      用到的是在网上烂大街的cheerio库来处理爬取的内容,使用superagent处理请求,log4js来记录日志。
      日志配置
      话不多说,直接上代码:
    1. const log4js = require('log4js');

    2. log4js.configure({
    3.   appenders: {
    4.     cheese: {
    5.       type: 'dateFile',
    6.       filename: 'cheese.log',
    7.       pattern: '-yyyy-MM-dd.log',
    8.       // 包含模型
    9.       alwaysIncludePattern: true,

    10.       maxLogSize: 1024,
    11.       backups: 3 }
    12.   },
    13.   categories: { default: { appenders: ['cheese'], level: 'info' } }
    14. });

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

    17. module.exports = logger;
    复制代码
     以上直接导出一个logger对象,在业务文件里直接调用logger.info()等函数添加日志信息就可以,会按天生成日志,相关信息网络上一堆。
    爬取内容并处理
    1. superagent.get(cityItemUrl).end((err, res) => {
    2.     if (err) {
    3.       return console.error(err);
    4.     }

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

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

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

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

    23.         fs.writeFileSync(path.join(__dirname, './imgs.json'), JSON.stringify(content));
    24.       });
    25.     });
    26.   });
    复制代码
    使用superagent请求页面,请求成功后使用cheerio 来加载页面内容,然后使用类似Jquery的匹配规则来查找目的资源。
      多个资源加载完成,使用eventproxy来代理事件,处理一次资源处罚一次事件,所有事件触发完成后处理数据。
      以上就是最基本的爬虫了,接下来就是一些可能会出问题或者需要特别注意的地方了。

      读写本地文件

      创建文件夹:
    1. function mkdirSync(dirname) {
    2.   if (fs.existsSync(dirname)) {
    3.     return true;
    4.   }
    5.   if (mkdirSync(path.dirname(dirname))) {
    6.     fs.mkdirSync(dirname);
    7.     return true;
    8.   }

    9.   return false;
    10. }
    复制代码
    读写文件:

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

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

    6.       fs.writeFileSync(path.join(__dirname, './dir.json'), JSON.stringify(content));
    复制代码
    批量下载资源
      下载资源可能包括图片、音频等等。
      使用Bagpipe处理异步并发:
    1. const Bagpipe = require('bagpipe');

    2. const bagpipe = new Bagpipe(10);

    3.     bagpipe.push(downloadImage, url, dstpath, (err, data) => {
    4.       if (err) {
    5.         console.log(err);
    6.         return;
    7.       }
    8.       console.log(`[${dstpath}]: ${data}`);
    9.     });
    复制代码
    下载资源,使用stream来完成文件写入。
    1. function downloadImage(src, dest, callback) {
    2.   request.head(src, (err, res, body) => {
    3.     if (src && src.indexOf('http') > -1 || src.indexOf('https') > -1) {
    4.       request(src).pipe(fs.createWriteStream(dest)).on('close', () => {
    5.         callback(null, dest);
    6.       });
    7.     }
    8.   });
    9. }
    复制代码
    编码
      有时候直接使用 cheerio.load处理的网页内容,写入文件后发现是编码后的文字,可以通过:
    1. const $ = cheerio.load(buf, { decodeEntities: false });
    复制代码
     来禁止编码。
      ps: encoding库和iconv-lite未能实现将utf-8编码的字符转换为中文,可能是还对API不熟悉,稍后可以关注下。
      最后,附上一个匹配所有dom标签的正则。
    1. const reg = /<.*?>/g;
    复制代码






    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-4-19 01:07 , Processed in 0.064188 second(s), 24 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表