nodejs实现一个简易的爬虫;使用cheerio实现在服务端使用dom操作
我们用nodejs的http模块实现一个简单的爬虫:
什么事爬虫呢?就是我们获取到网页上面的一些数据信息,我们把它爬下来,爬到本地。比如说我们可以爬图片、爬html文档等。
下面来简单实现以下,如何去爬一个网页:
const https = require("https")
const fs = require("fs")
// 使用http的get方法,来爬去小滴课堂官网的数据 这里需要注意 我们爬取的是 https的网页 用的是https模块
https.get("https://xdclass.net/#/index",res => {
//设置一下编码格式
res.setEncoding('utf8');
// 创建一个html变量
let html = '';
// 监听response的data事件,将获取到的数据 保存在 html 变量中
res.on('data',chunk => {
html += chunk;
})
// 监听一下 响应结束的方法
res.on('end',()=>{
console.log(html);
// 用fs模块的writeFile方法,将网页内容 写入到index.txt文件中 这个方法会自动创建文件
fs.writeFile('./index.txt',html,(err)=>{
if(err) throw err;
console.log("写入成功");
})
})
})
使用cheerio的npm包 实现dom操作
cheerio的一个中文文档:https://www.jianshu.com/p/629a81b4e013
cheerio是jquery核心功能的一个快速灵活而又简洁的实现,主要是为了用在服务器端需要对DOM进行操作的地方
首先本地安装:
npm init -y 初始化以下node项目 生成package.json文件
npm install cheerio --save-dev
根据以上爬虫的代码,添加cheerio的使用案例
const https = require("https")
const fs = require("fs")
const cheerio = require("cheerio")
// 使用http的get方法,来爬去小滴课堂官网的数据 这里需要注意 我们爬取的是 https的网页 用的是https模块
https.get("https://xdclass.net/#/index",res => {
//设置一下编码格式
res.setEncoding('utf8');
// 创建一个html变量
let html = '';
// 监听response的data事件,将获取到的数据 保存在 html 变量中
res.on('data',chunk => {
html += chunk;
})
// 监听一下 响应结束的方法
res.on('end',()=>{
// cheerio的使用
// 先用cheerio的load方法将html加载进去
const $ = cheerio.load(html);//这一步之后就可以用jquery的方式来进行dom操作了
console.log($("title").text());//通过获取title元素获取其文本
// 用fs模块的writeFile方法,将网页内容 写入到index.txt文件中 这个方法会自动创建文件
fs.writeFile('./index.txt',html,(err)=>{
if(err) throw err;
console.log("写入成功");
})
})
})
。

浙公网安备 33010602011771号