Node.js(十三)——Promise重构爬虫代码
在重构代码之前,先要了解下什么是https?
https协议:基于ssl/tls的http协议,所有的数据都是在
ssl/tls协议的封装之上传输的,也就是说https协议是在http协议基础上
添加了ssl/tls握手以及数据加密传输,因此这就是两者之间最大的区别。
https模块专门处理加密访问的,区别在于搭建https服务器的时候需要有ssl证书。
模拟搭建https服务器
varhttps=require('https')varfs=require('fs')//文件系统模块varoptions={//同步的读出ssl证书__虚拟key:fs.readFileSync('ssh_key.pem')cert:fs.readFileSync('ssh_cert.pem')}//通过以上读取证书之后就可以运行https服务器https.createServer(options,function(req,res){res.wirteHead(200)res.end('HelloHttps')}).listen(8090)
重构爬虫代码:
varhttp=require('http')varcheerio=require('cheerio')//在新版本中Promise已经内置varpromise=require('bluebird')varbaseUrl='http://www.imooc.com/learn/'varvideoIds=[348,259,197,134,751]functionfilterChapters(html){var$=cheerio.load(html)varchapters=$('.mod-chapters')//标题vartitle=$('#main.pathspan').text()//学习的人数//varnumber=parseInt($($('static-item')[0]).text().trim(),10)//varnumber=$($('.static-itemspan')[1]).text();//varnumber=parseInt($('.meta-valuejs-learn-num').text().trim(),10)varnumber=$('.meta-valuejs-learn-num').html()varcourseData={title:title,number:number,videos:[]}//遍历的里面拿到数据chapters.each(function(item){varchapter=$(this);//章节标题varchapterTitle=chapter.find('strong').text()console.log(chapterTitle)varvideos=chapter.find('.video').children('li')varchapterData={chapterTitle:chapterTitle,videos:[]}//遍历videosvideos.each(function(item){varvideo=$(this).find('.J-media-item')varvideoTitle=video.text()varid=video.attr('href').split('video/')[1]chapterData.videos.push({title:videoTitle,id:id})})courseData.videos.push(chapterData)})returncourseData}functionprintCourseInfo(coursesData){coursesData.forEach(function(courseData){console.log(courseData.number+'人学过'+courseData.title+'\n')})//数组中的遍历coursesData.forEach(function(courseData){console.log('###'+courseData.title+'\n')courseData.videos.forEach(function(item){varchapterTitle=item.chapterTitleitem.videos.forEach(function(video){console.log('【'+video.id+'】'+video.title);})})})}functiongetPageAsync(url){returnnewPromise(function(resolve,reject){console.log('正在抓取'+url)http.get(url,function(res){varhtml=''res.on('data',function(data){html+=data})res.on('end',function(){//在请求完成的时候,通过resolve传递下去resolve(html)}).on('error',function(e){//如果出错了reject(e)console.log('获取页面出错')})})})}varfetchCourseArray=[]videoIds.forEach(function(id){//遍历的结果传递过去fetchCourseArray.push(getPageAsync(baseUrl+id))})//需要做并发控制,全部去爬Promise.all(fetchCourseArray).then(function(pages){//多页面处理varcoursesData=[]//对page进行加工pages.forEach(function(html){//对html进行解析varcourses=filterChapters(html)coursesData.push(courses)})//遍历coursesData.sort(function(a,b){returna.number<b.number})printCourseInfo(coursesData)})
运行结果如下:
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。