Node微信公众号开发 cheerio网页抓取和memory-cache缓存模块

こ雲淡風輕ζ 提交于 2020-03-09 12:53:29

模块介绍

本文将介绍三款模块。之所以标题中只出现了两款,是由于目前我的公众号 cron 定时模块暂未使用:

  • cheerio

    插件介绍:Fast, flexible & lean implementation of core jQuery designed specifically for the server.

    通俗易懂大白话:允许 node.js 像 jQurey 那样获取页面 DOM 节点

  • memory-cache

    插件介绍:A simple in-memory cache for node.js

    通俗易懂大白话:就是一个数据缓存模块

  • cron

    插件介绍:Cron is a tool that allows you to execute something on a schedule. This is typically done using the cron syntax. We allow you to execute a function whenever your scheduled job triggers. We also allow you to execute a job external to the javascript process using child_process. Additionally, this library goes beyond the basic cron syntax and allows you to supply a Date object. This will be used as the trigger for your callback. Cron syntax is still an acceptable CronTime format. Although the Cron patterns supported here extend on the standard Unix format to support seconds digits, leaving it off will default to 0 and match the Unix behavior.

    通俗易懂大白话:一个定时器,允许 node.js 可以按照一定时间规律或者时间节点去执行某项操作

运用以上模块,对我个人的公众号做了如下修改:

  • access_token 存储方式由 fs.writeFile 写入本地文件改为利用缓存
  • 由于 wp-json 会导致原站点安全性降低,故数据获取改用 cheerio 爬取网站内容对象获得

cheerio

安装:

npm install cheerio

用法:

<ul id="fruits">
  <li class="apple">Apple</li>
  <li class="orange">Orange</li>
  <li class="pear">Pear</li>
</ul>

html 页面结构示例如上,模块官方使用基础方式如下

const cheerio = require('cheerio'); // 首先,引入模块
const $ = cheerio.load('<ul id="fruits">...</ul>'); // 直接获取页面 #fruits 节点
// 也可以是这样
$('ul', '<ul id="fruits">...</ul>');
// 又或者是这样
$('li', 'ul', '<ul id="fruits">...</ul>');

官网示例似乎都是使用该模块去创建 DOM 的操作,更多的用法还请参考官网查阅 cheerio

而在这里我需要使用模块去抓取网站的内容,所以我使用的方法如下

const cheerio = require('cheerio'); // 首先,引入模块
const $ = cheerio.load(html) // 获取整个 html 节点
const eleUl = $.find('#fruits')
const appleTxt = $.find('#fruits .apple').text()

这样就可以对于 DOM 节点进行友好的操控了,具体使用方法 jQuery 如出一辙

实例:

我的目标网站 http://www.demo.com 的 DOM 结构如下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <dl>
    <dt>标题1</dt>
    <dd>文章简介1</dd>
  </dl>
  <dl>
    <dt>标题2</dt>
    <dd>文章简介2</dd>
  </dl>
  <dl>
    <dt>标题3</dt>
    <dd>文章简介3</dd>
  </dl>
</body>
</html>

这是我们只需要请求该地址,获取到页面数据后使用 cheerio 对页面有效内容进行提取,从而建立起该网页的数据文档

const request = require('request'); // 引入请求模块
const cheerio = require('cheerio'); // 引入 cheerio 模块
request.get('http://www.demo.com', function (err, res, body) {
    var $ = cheerio.load(html)
    var obj = [] // 空数组,用于存放数据
    $('dl').each((index, element) => { // 循环页面 DOM
        obj.push = { // 生成最终数据对象
			title: $(element).find('dt').text(),
			excerpt: $(element).find('dd').text()
        }
    })    
})

上述代码中最终获得了页面数据 obj 对象


memory-cache

安装:

npm install memory-cache --save

用法:

var cache = require('memory-cache');
cache.put('foo', 'bar'); // 存储缓存
cache.get('foo'); // 使用缓存

基础用法如上,我们也可以进行如下操作

cache.put('houdini', 'disappear', 100, function(key, value) {
    console.log(key + ' did ' + value);
});
// 参数 1 为需存储的缓存名称
// 参数 2 为 houdini 的缓存内容
// 参数 3 为缓存到期时间(该时间是从当前时间开始到过期这段这段时间的用时)
// 参数 4 回调函数

这里对于过期时间需要注意,这里的时间是 从当前时间开始到过期这段这段时间的用时

它不仅如此可以实现存储与读取,更提供了更多的操作可能,简单粗暴,似乎也没有什么更多的解释,官方介绍如下

  • del = function(key)

    删除密钥,返回一个布尔值,指定是否删除密钥

  • clear = function()

    删除所有键

  • memsize = function()

    返回占用缓存空间的条目数

  • debug = function(bool)

    打开或关闭调试

  • hits = function()

    返回缓存命中数(仅在调试模式下监视)

  • misses = function()

    返回缓存未命中的数量(仅在调试模式下监视)

  • keys = function()

    返回所有缓存键

  • exportJson = function()

    返回表示所有缓存数据的 JSON 字符串

  • importJson = function(json: string, options: { skipDuplicates: boolean })

    合并以前调用的所有数据以导出到缓存中

  • Cache = function()

    缓存构造函数

文本英文很差,所以更详细说明还请参考官网查阅 memory-cache


cron

安装:

npm install cron

用法:

var CronJob = require('cron').CronJob; // 引入模块并调用模块 CronJob 方法
var job = new CronJob('* * * * * *', function() { // 创建定时器
	console.log('You will see this message every second');
}, null, true, 'America/Los_Angeles');
job.start(); // 执行定时器

// constructor(cronTime, onTick, onComplete, start, timezone, context, runOnInit, unrefTimeout)
// cronTime [必需] 配置定时任务的时间,可以使用这可以是 cron 语法或 JS Date 对象的形式
// onTick [必需]在指定时间触发的回调
// onComplete [可选] 在作业停止时将触发的回调
// Start [可选]指定是否在退出构造函数之前启动作业,默认情况下,此值设置为 false
// timeZone [可选] -指定执行的时区。这将修改相对于您的时区的实际时间 ,不设置为当前所在时区。设置为Europe/London 为 UTC 0 时区

官方的用法如上,对于其中 cronTime 值, Nodejs 定时执行(node-cron) 给出的解释更为详细,如下

秒:0-59
分钟:0-59
小时:0-23
天:1-31
月份:0-11(1月至12月)
星期几:0-6(周日至周六)

排列顺序

*为通配符
-为时间段连接符
,号为分隔符,可以在某一节输入多个值
/号为步进符

官方示例中 * * * * * * 意思为均通配,导致结果就是每秒都执行

要在每次分钟时间为10的时候执行 * 10 * * * *

执行结果为每天14点05分10秒时执行语句 10 05 14-17 * * *

执行结果为每天14-17点的05分10秒时执行语句 11,22,25 * * * * *

也可以控制间隔多少时间执行(循环)*/3 * * * * * 间隔3秒执行,0 */2 * * * * 间隔两分钟执行

由于没有在公众号上实践,这里就不做更多赘述,还请参考官网查阅 cron


文章已同步我的个人博客:《Node微信公众号 cheerio网页抓取和memory-cache缓存模块


资料参考:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!