demo

cheerio这个模块是用来解析html代码的。
cheerio是node.js的抓取页面模块,为服务器特别定制的,快速,灵活,实施的jQuery核心实现。适合各种web爬虫程序。

通俗的讲:cheerio模板可以让我们用jquery语法来解析爬取的网页的数据。

1.定时任务结合cheerio模块实现爬虫系统,检查网站是否被篡改

  1. //service/spider.js
  2. const Service = require('egg').Service;
  3. class SpiderService extends Service {
  4. /* 抓取数据的service */
  5. async requestUrl(url) {
  6. let result = await this.ctx.curl(url);
  7. return result
  8. }
  9. }
  10. module.exports = SpiderService;
  1. //schedule/watch.js
  2. const cheerio = require('cheerio')
  3. module.exports = {
  4. schedule: {
  5. interval: '5s', // 1 分钟间隔
  6. type: 'all', // 指定所有的 worker 都需要执行
  7. },
  8. async task(ctx) {
  9. let url = "https://news.baidu.com/";
  10. let result = await ctx.service.spider.requestUrl(url);
  11. //抓取数据
  12. let htmlData = result.data.toString();
  13. //解析数据
  14. const $ = cheerio.load(htmlData,{decodeEntities:false});
  15. let title = $('title').html();
  16. if(title !='百度新闻——海量中文资讯平台'){
  17. console.log('网站挂掉了')
  18. }else{
  19. console.log('正常')
  20. }
  21. }
  22. };