1、爬取百度新闻数据。javascript
①首先看下咱们要爬取的网站数据:news.baidu.comhtml
②首先在service>spider.js下写入以下方法,写一个requestUrl方法 传入url并获取数据。java
"use strict"; const Controller = require("egg").Controller; class SpiderController extends Controller { async requestUrl(url) { var result = await this.ctx.curl(url); return result; } } module.exports = SpiderController;
③schedule下新建一个定时任务watchdomin,写入以下方法,每5s调用一次数据:node
module.exports = app => { return { schedule: { interval: "5s", type: "all" }, async task(ctx) { var url = "https://news.baidu.com/"; var result = await ctx.service.spider.requestUrl(url); console.log(result); } }; };
④由控制台可知,爬取到了数据:jquery
⑤对spider.js稍做改动,则可知打印出来的数据是一堆页面信息。npm
2、检测网站是否挂掉。服务器
首先介绍cheerio模块:app
cheerio是nodejs的抓取页面模块,为服务器特别定制的,快速、灵活、实施的jQuery核心实现,适合各类Web爬虫程序。dom
通俗地讲:cheerio模块能够让咱们用jquery语法来解析爬取的网页数据。curl
https://www.npmjs.com/package/cheerio
cheerio的用法:
①安装cnpm i cheerio --save
②加载要解析的内容 const $ = cheerio.load('<h2 class="title">Hello World</h2>')
③$('title').html() 获取要匹配的标题内容。
将watchdomin.js作一些修改:
var cheerio = require("cheerio"); module.exports = app => { return { schedule: { interval: "5s", type: "all" }, async task(ctx) { var url = "https://news.baidu.com/"; var result = await ctx.service.spider.requestUrl(url); var htmlData = result.data.toString(); // 检测网站是否被篡改,检测网站是否会挂掉 const $ = cheerio.load(htmlData); console.log($("title").html()); } }; };
可得打印出来的title是一堆乱码,那么,如何解决呢?load方法里面穿入一个配置参数{ decodeEntities: false },则打印出正常中文。
实现相似网站监控,看title的值有无被篡改:
var cheerio = require("cheerio"); module.exports = app => { return { schedule: { interval: "5s", type: "all" }, async task(ctx) { var url = "https://news.baidu.com/"; var result = await ctx.service.spider.requestUrl(url); var htmlData = result.data.toString(); // 检测网站是否被篡改,检测网站是否会挂掉 const $ = cheerio.load(htmlData, { decodeEntities: false }); var title = $("title").html(); if (title != "百度新闻——海量中文资讯平台") { console.log("网站挂掉了,或者被篡改了"); } else { console.log("正常"); } } }; };
爬取其余数据的基本写法,与jquery基本相似。
打完收工。