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("写入成功"); }) }) })
。
分类:
node
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
2019-06-25 vue 监听键盘回车事件 @keyup.enter || @keyup.enter.native