nodeJs 爬虫路上的技术点

news/2024/7/19 10:20:08 标签: 爬虫, javascript, json

背景

最近打算把之前看过的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;


http://www.niftyadmin.cn/n/1661793.html

相关文章

Mongodb集群部署

数据副本 MongoDB中的一组副本是一群mongod进程&#xff0c;这些进程维护同样的数据集。副本集提供了冗余和高可用性&#xff0c;是生产环境部署的基础。 数据冗余和可用性 通过在不同的服务器上存储相同的数据&#xff0c;副本机制保证了一定程度的容错&#xff0c;即在一个数…

两个对象用equals方法比较为true,它们的Hashcode值相同吗?

两个对象用equals方法比较为true&#xff0c;它们的Hashcode值相同吗&#xff1f; 答&#xff1a;不一定相同。正常情况下&#xff0c;因为equals()方法比较的就是对象在内存中的值&#xff0c;如果值相同&#xff0c;那么Hashcode值也应该相同。但是如果不重写hashcode方法&am…

dubbo-admin安装和使用

更新下链接&#xff0c;不知道是不是这个项目合入Apache的缘故&#xff0c;链接都变成了https://github.com/apache/incubator-dubbo/ 按照常理&#xff0c;直接去 https://github.com/alibaba/dubbo(https://github.com/apache/incubator-dubbo) 下载&#xff0c;然后进入下面…

swagger 指定字段不显示到文档里

Swagger UI 隐藏指定接口类或方法 - 宁静致远 - CSDN博客https://blog.csdn.net/lqh4188/article/details/53538201 swagger 指定字段不显示到文档里 - 帆帆爱苹果 - CSDN博客https://blog.csdn.net/mengxiangxingdong/article/details/82713008 Swagger使用文档 - 不能说的秘密…

学习笔记之NumPy

NumPy — NumPy http://www.numpy.org/NumPy is the fundamental package for scientific computing with Python.NumPy - Wikipedia https://en.wikipedia.org/wiki/NumPyNumPy (pronounced /ˈnʌmpaɪ/ (NUM-py) or sometimes /ˈnʌmpi/[1][2] (NUM-pee)) is a library for…

php中嵌套html代码和html代码中嵌套php方式

php中嵌套html代码和html代码中嵌套php方式 一、总结 拷贝的话直接html代码是极好的方式 1、php中嵌套html代码&#xff08;本质是原生php&#xff09;&#xff1a;a、原生嵌套<?php .....?> b、标签&#xff0c;例如&#xff1a;{:url(index/index)} 2、html…

【android】Android Studio 入门采坑

安卓的环境搭建起来真不容易&#xff0c;介绍一下&#xff1a; 1. 安装JDK JDK是Java开发工具包&#xff0c;需要1.8版本以上&#xff0c;Mac下直接用homebrew安装&#xff1a; brew cask install java安装成功后&#xff0c;检查 java -version2. 下载 Andriod Studio 直接谷歌…

当一个对象被当做参数传递到一个方法后,此方法可改变这个对象的属性,并可返回变化后的结果,那么这里到底是值传递还是引用传递?

当一个对象被当做参数传递到一个方法后&#xff0c;此方法可改变这个对象的属性&#xff0c;并可返回变化后的结果&#xff0c;那么这里到底是值传递还是引用传递&#xff1f; 答&#xff1a;是值传递。Java编程语言中只有由值传递参数的。当一个对象实例作为一个参数被传递到方…