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

相关文章

springboot如何通过http动态操作xxl-job任务

《springboot如何通过http动态操作xxl-job任务》:本文主要介绍springboot如何通过http动态操作xxl-job任务的问题,具有很好的参考价值,希望对大家有所帮助,如有错... 目录springboot通过http动态操作xxl-job任务一、maven依赖二、配置文件三、xxl-

Nginx 重写与重定向配置方法

《Nginx重写与重定向配置方法》Nginx重写与重定向区别:重写修改路径(客户端无感知),重定向跳转新URL(客户端感知),try_files检查文件/目录存在性,return301直接返回永久重... 目录一.try_files指令二.return指令三.rewrite指令区分重写与重定向重写: 请求

Maven 配置中的 <mirror>绕过 HTTP 阻断机制的方法

《Maven配置中的<mirror>绕过HTTP阻断机制的方法》:本文主要介绍Maven配置中的<mirror>绕过HTTP阻断机制的方法,本文给大家分享问题原因及解决方案,感兴趣的朋友一... 目录一、问题场景:升级 Maven 后构建失败二、解决方案:通过 <mirror> 配置覆盖默认行为1. 配置示

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Linux中修改Apache HTTP Server(httpd)默认端口的完整指南

《Linux中修改ApacheHTTPServer(httpd)默认端口的完整指南》ApacheHTTPServer(简称httpd)是Linux系统中最常用的Web服务器之一,本文将详细介绍如何... 目录一、修改 httpd 默认端口的步骤1. 查找 httpd 配置文件路径2. 编辑配置文件3. 保存

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

使用Python获取JS加载的数据的多种实现方法

《使用Python获取JS加载的数据的多种实现方法》在当今的互联网时代,网页数据的动态加载已经成为一种常见的技术手段,许多现代网站通过JavaScript(JS)动态加载内容,这使得传统的静态网页爬取... 目录引言一、动态 网页与js加载数据的原理二、python爬取JS加载数据的方法(一)分析网络请求1

C++ HTTP框架推荐(特点及优势)

《C++HTTP框架推荐(特点及优势)》:本文主要介绍C++HTTP框架推荐的相关资料,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. Crow2. Drogon3. Pistache4. cpp-httplib5. Beast (Boos

SpringBoot中HTTP连接池的配置与优化

《SpringBoot中HTTP连接池的配置与优化》这篇文章主要为大家详细介绍了SpringBoot中HTTP连接池的配置与优化的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录一、HTTP连接池的核心价值二、Spring Boot集成方案方案1:Apache HttpCl

重新对Java的类加载器的学习方式

《重新对Java的类加载器的学习方式》:本文主要介绍重新对Java的类加载器的学习方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍1.1、简介1.2、符号引用和直接引用1、符号引用2、直接引用3、符号转直接的过程2、加载流程3、类加载的分类3.1、显示