demo
cheerio这个模块是用来解析html代码的。
cheerio是node.js的抓取页面模块,为服务器特别定制的,快速,灵活,实施的jQuery核心实现。适合各种web爬虫程序。
通俗的讲:cheerio模板可以让我们用jquery语法来解析爬取的网页的数据。
1.定时任务结合cheerio模块实现爬虫系统,检查网站是否被篡改
//service/spider.jsconst Service = require('egg').Service;class SpiderService extends Service {/* 抓取数据的service */async requestUrl(url) {let result = await this.ctx.curl(url);return result}}module.exports = SpiderService;
//schedule/watch.jsconst cheerio = require('cheerio')module.exports = {schedule: {interval: '5s', // 1 分钟间隔type: 'all', // 指定所有的 worker 都需要执行},async task(ctx) {let url = "https://news.baidu.com/";let result = await ctx.service.spider.requestUrl(url);//抓取数据let htmlData = result.data.toString();//解析数据const $ = cheerio.load(htmlData,{decodeEntities:false});let title = $('title').html();if(title !='百度新闻——海量中文资讯平台'){console.log('网站挂掉了')}else{console.log('正常')}}};
