egg(17)--定時任務schedule,監聽網站是否被修改,cheerio爬蟲
阿新 • • 發佈:2019-02-03
目錄結構
檔案內容
安裝依賴
cnpm install cheerio --save
service/spider.js
'use strict';
const Service = require('egg').Service;
class SpiderService extends Service {
async requestUrl(url) {
var result = await this.ctx.curl(url);
return result;
}
}
module.exports = SpiderService;
schedule/watchdomain.js
var cheerio = require('cheerio') module.exports = (app) => { return { schedule:{ interval:'10s', type:'all' }, async task(ctx){ var url = 'https://news.baidu.com/'; var result = await ctx.service.spider.requestUrl(url); //buff資料轉為utf8 var htmlData = result.data.toString(); // 亂碼轉為utf8 const $ = cheerio.load(htmlData,{decodeEntities:false}) // 拿到網站標題 var title = $('title').html(); if(title != '百度新聞——全球最大的中文新聞平臺'){ console.log("網站被修改了") }else{ console.log("正常") } //根據class拿到資料 $('.hotnews a').each(function(){ console.log($(this).html()) }) } } }
網站內容
cheerio爬蟲拿到資料,解析