一、爬取百度新闻数据。
①首先看下我们要爬取的网站数据:news.baidu.com
②首先在service>spider.js下写入如下方法,写一个requestUrl方法 传入url并获取数据。
"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调用一次数据:
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);
}
};
};
④由控制台可知,爬取到了数据:
⑤对spider.js稍作改动,则可知打印出来的数据是一堆页面信息。
二、检测网站是否挂掉。
首先介绍cheerio模块:
cheerio是nodejs的抓取页面模块,为服务器特别定制的,快速、灵活、实施的jQuery核心实现,适合各种Web爬虫程序。
通俗地讲:cheerio模块可以让我们用jquery语法来解析爬取的网页数据。
cheerio的用法:
①安装cnpm i cheerio --save
②加载要解析的内容 const $ = cheerio.load("
Hello World
")③$("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基本类似。
打完收工。