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

相关文章

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. 发送

Unity新手入门学习殿堂级知识详细讲解(图文)

《Unity新手入门学习殿堂级知识详细讲解(图文)》Unity是一款跨平台游戏引擎,支持2D/3D及VR/AR开发,核心功能模块包括图形、音频、物理等,通过可视化编辑器与脚本扩展实现开发,项目结构含A... 目录入门概述什么是 UnityUnity引擎基础认知编辑器核心操作Unity 编辑器项目模式分类工程

Python学习笔记之getattr和hasattr用法示例详解

《Python学习笔记之getattr和hasattr用法示例详解》在Python中,hasattr()、getattr()和setattr()是一组内置函数,用于对对象的属性进行操作和查询,这篇文章... 目录1.getattr用法详解1.1 基本作用1.2 示例1.3 原理2.hasattr用法详解2.

Go语言使用net/http构建一个RESTful API的示例代码

《Go语言使用net/http构建一个RESTfulAPI的示例代码》Go的标准库net/http提供了构建Web服务所需的强大功能,虽然众多第三方框架(如Gin、Echo)已经封装了很多功能,但... 目录引言一、什么是 RESTful API?二、实战目标:用户信息管理 API三、代码实现1. 用户数据

Python WSGI HTTP服务器Gunicorn使用详解

《PythonWSGIHTTP服务器Gunicorn使用详解》Gunicorn是Python的WSGI服务器,用于部署Flask/Django应用,性能高且稳定,支持多Worker类型与配置,可处... 目录一、什么是 Gunicorn?二、为什么需要Gunicorn?三、安装Gunicorn四、基本使用启

Spring Security重写AuthenticationManager实现账号密码登录或者手机号码登录

《SpringSecurity重写AuthenticationManager实现账号密码登录或者手机号码登录》本文主要介绍了SpringSecurity重写AuthenticationManage... 目录一、创建自定义认证提供者CustomAuthenticationProvider二、创建认证业务Us