node.js学习笔记--HTTP之Promise重写小爬虫

2024-01-28 16:18

本文主要是介绍node.js学习笔记--HTTP之Promise重写小爬虫,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

注:此博客是在学习进击Node.js基础(一)这门课程时的学习笔记,感谢Scott老师的课程。

一、使用Promise处理异步、嵌套

1. 用传统的回调来按顺序执行小球动画

<!doctype>
<html>
<head><title>Promise animation</title><style>.ball{width: 40px;height:40px;border-radius: 20px;}.ball1{background: red;}.ball2{background: yellow;}.ball3{background: green;}</style><!-- 引用bluebird这个库来使用promise函数,bluebird被我下在了Desktop的上一级,administrator文件夹里 --><script scr="C:\Users\Administrator\node_modules\bluebird\js\browser\bluebird.js"></script>
</head>
<body><div class='ball ball1' style="margin-left: 0;"></div><div class='ball ball2' style="margin-left: 0;"></div><div class='ball ball3' style="margin-left: 0;"></div><script>var ball1 = document.querySelector('.ball1')var ball2 = document.querySelector('.ball2')var ball3 = document.querySelector('.ball3')console.log(ball1)function animate(ball, distance, callback){setTimeout(function(){var marginLeft = parseInt(ball.style.marginLeft, 10)//如果小球到达目标点,即动画已经执行完毕,就执行回调函数if(marginLeft === distance){callback && callback()}else{if(marginLeft < distance){  //球在左侧,就往右移marginLeft++}else{marginLeft--}ball.style.marginLeft = marginLeftanimate(ball, distance, callback)  //继续调用自身animate,不断重复调整小球位置,直到移到目标位置}}, 13)   //设定间隔多少时间执行函数,13毫秒一次}       //传统的按顺序执行调用函数//第一个球向右移动100像素,然后执行移动第二个球,第二个球向右移动200像素,然后执行移动第三个球...animate(ball1, 100, function(){animate(ball2, 200, function(){animate(ball3, 300, function(){animate(ball3, 150, function(){animate(ball2, 150, function(){animate(ball1, 150, function(){//})})})})})})</script>
</body>
</html>

效果:
这里写图片描述
2.用Promise方法重写一遍同样的按顺序执行小球动画

调用bluebird里的promise函数,和上面的逻辑一样,但是函数申明的方式不一样。而且对比上面的嵌套写法,如果想要更改小球的顺序或者加其他动作,上面的写法就很麻烦。相比,用Promise,每个动作的顺序关系就是线性的。一个Promise是一个带有.then()方法的对象,是异步编程的抽象。

<!doctype>
<html>
<head><title>Promise animation</title><style>.ball{width: 40px;height:40px;border-radius: 20px;}.ball1{background: red;}.ball2{background: yellow;}.ball3{background: green;}</style><!-- 引用bluebird这个库来使用promise函数,bluebird被我下在了Desktop的上一级,administrator文件夹里 --><script scr="C:\Users\Administrator\node_modules\bluebird\js\browser\bluebird.js"></script>
</head>
<body><div class='ball ball1' style="margin-left: 0;"></div><div class='ball ball2' style="margin-left: 0;"></div><div class='ball ball3' style="margin-left: 0;"></div><script>var ball1 = document.querySelector('.ball1')var ball2 = document.querySelector('.ball2')var ball3 = document.querySelector('.ball3')console.log(ball1)var Promise = window.Promise //不过现在好像原生支持Promise,不需要引入库了function promiseAnimate(ball, distance){return new Promise(function(resolve, reject){function _animate(){  //下划线表示_animate是私有函数setTimeout(function(){  //定时器var marginLeft = parseInt(ball.style.marginLeft, 10)if(marginLeft === distance){resolve()  //如果小球到达目标点,即动画已经执行完毕,就执行回调函数}else{if(marginLeft < distance){  //球在左侧,就往右移marginLeft++}else{marginLeft--}ball.style.marginLeft = marginLeft + 'px'_animate() //调用自身}}, 13)   //设定间隔多少时间执行函数,13毫秒一次}_animate() //启动第一次调用})}//原理: .then()函数总是返回一个新的Promise,then()里可放两个参数,第一个为前面函数执行成功的返回函数,第二个为执行不成功的返回函数promiseAnimate(ball1, 100).then(function(){return promiseAnimate(ball2, 200)}).then(function(){return promiseAnimate(ball3, 300)}).then(function(){return promiseAnimate(ball3, 150)}).then(function(){return promiseAnimate(ball2, 150)}).then(function(){return promiseAnimate(ball1, 150)})</script>
</body>
</html>

二、用Promise重写小爬虫

重写上一篇里的node.js学习笔记–HTTP之小爬虫。

//用Promise来重构小爬虫,去除之前的回调
var http = require('http')
var Promise = require('Promise') //新版本的nodejs可以直接引用Promise了
var cheerio = require('cheerio')   //一个像JQuery语法一样可以提供快捷检索的库
var url = 'http://www.imooc.com/learn/348'
var baseUrl = 'http://www.imooc.com/learn/'function filterChapters(html){var $ = cheerio.load(html)var chapters = $('.mod-chapters')//网页上的数据结构// courseData = {//      [{//      chapterTitle: '',//      videos: [//          title: '',//          id: ''//      ]//      }]// }var courseData = []//对每一章进行遍历chapters.each(function(item){var chapter = $(this) //拿到每个单独的章节var chapterTitle = chapter.find('strong').text()var videos =  chapter.find('.video').children('li')var chapterData = {chapterTitle: chapterTitle,videos: []} //组装对象//对videos进行遍历videos.each(function(item){var video = $(this).find('.J-media-item') //拿到每个单独的video里的classvar videosTitle = video.text() //返回该元素下的所有文本内容var id =  video.attr('href').split('video/')[1]  //要拿到href链接里video/后的内容即视频idchapterData.videos.push({title: videosTitle,id: id})})courseData.push(chapterData) //把拿好的章节数据放进数组})return courseData
}function printCourseInfo(courseData){courseData.forEach(function(item){  //对courseData这个数组进行遍历var chapterTitle = item.chapterTitleconsole.log(chapterTitle + '\n')item.videos.forEach(function(video){console.log('(' + video.id + ')' + video.title + '\n')})})
}function getPageAsync(url){return new Promise(function(resolve, reject){console.log('正在爬取 ' + url)http.get(url, function(res){var html = ''res.on('data', function(data){html += data})  //收到数据data时这个事件就会不断被触发,html字符串就不断累加res.on('end',function(){resolve(html)//var courseData = filterChapters(html) //原来的回调写法//printCourseInfo(courseData)})  //end事件}).on('error', function(){reject(e)console.log('获取课程数据出错')})//http.get还可以注册error事件,当出现异常时能捕捉错误})
}//可同步爬取多个课程
var fetchCourseaArray = []videoIds.forEach(function(id){fetchCourseaArray.push(getPageAsync(baseUrl + id))
})Promise.all(fetchCourseaArray).then(function(pages){var coursesData = []pages.forEach(function(html){var courses = filterChapters(html) //解析htmlcoursesData.push(courses)})})

这篇关于node.js学习笔记--HTTP之Promise重写小爬虫的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/654137

相关文章

Java方法重载与重写之同名方法的双面魔法(最新整理)

《Java方法重载与重写之同名方法的双面魔法(最新整理)》文章介绍了Java中的方法重载Overloading和方法重写Overriding的区别联系,方法重载是指在同一个类中,允许存在多个方法名相同... 目录Java方法重载与重写:同名方法的双面魔法方法重载(Overloading):同门师兄弟的不同绝

JS纯前端实现浏览器语音播报、朗读功能的完整代码

《JS纯前端实现浏览器语音播报、朗读功能的完整代码》在现代互联网的发展中,语音技术正逐渐成为改变用户体验的重要一环,下面:本文主要介绍JS纯前端实现浏览器语音播报、朗读功能的相关资料,文中通过代码... 目录一、朗读单条文本:① 语音自选参数,按钮控制语音:② 效果图:二、朗读多条文本:① 语音有默认值:②

在Node.js中使用.env文件管理环境变量的全过程

《在Node.js中使用.env文件管理环境变量的全过程》Node.js应用程序通常依赖于环境变量来管理敏感信息或配置设置,.env文件已经成为一种流行的本地管理这些变量的方法,本文将探讨.env文件... 目录引言为什么使php用 .env 文件 ?如何在 Node.js 中使用 .env 文件最佳实践引

Java 中的 equals 和 hashCode 方法关系与正确重写实践案例

《Java中的equals和hashCode方法关系与正确重写实践案例》在Java中,equals和hashCode方法是Object类的核心方法,广泛用于对象比较和哈希集合(如HashMa... 目录一、背景与需求分析1.1 equals 和 hashCode 的背景1.2 需求分析1.3 技术挑战1.4

使用Node.js和PostgreSQL构建数据库应用

《使用Node.js和PostgreSQL构建数据库应用》PostgreSQL是一个功能强大的开源关系型数据库,而Node.js是构建高效网络应用的理想平台,结合这两个技术,我们可以创建出色的数据驱动... 目录初始化项目与安装依赖建立数据库连接执行CRUD操作查询数据插入数据更新数据删除数据完整示例与最佳

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

Three.js构建一个 3D 商品展示空间完整实战项目

《Three.js构建一个3D商品展示空间完整实战项目》Three.js是一个强大的JavaScript库,专用于在Web浏览器中创建3D图形,:本文主要介绍Three.js构建一个3D商品展... 目录引言项目核心技术1. 项目架构与资源组织2. 多模型切换、交互热点绑定3. 移动端适配与帧率优化4. 可

HTTP 与 SpringBoot 参数提交与接收协议方式

《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

使用Python的requests库来发送HTTP请求的操作指南

《使用Python的requests库来发送HTTP请求的操作指南》使用Python的requests库发送HTTP请求是非常简单和直观的,requests库提供了丰富的API,可以发送各种类型的HT... 目录前言1. 安装 requests 库2. 发送 GET 请求3. 发送 POST 请求4. 发送