之前的网络小爬虫只可以爬http,https不可以,原因在这里。
https协议:是基于SSL/TLS的http协议,也就是说https是在http协议上增加了ssl/tls握手以及数据加密传输。
构建一个https服务器:
//引入一个https模块
var https = require('https')
//引入文件系统fs模块
var fs = require('fs')
//创建一哥options对象字面量
var options = {
//私钥文件
key:fs.readFileSync('ssh_key.pem'),
//证书文件
cert:fs.readFileSync('ssh_cert.pem')
}
//本地有量key,cert文件之后就可以运行https服务器了
https
.createServer(options, function(req, res) {
res.writeHead(200)
res.end('hello world')
})
//监听端口
.listen(8080)
使用promise进行网络爬虫优化:
一下代码可直接获取页面信息
var http = require('http')
//使用npm install cheerio(相当于jq)
var cheerio = require('cheerio')
//新的nodejs里面有promise模块,未来保险起见,我们还是引入外部的bluebrid库(npm install bluebrid)
var Promise = require('bluebird')
var baseUrl = 'http://www.imooc.com/learn/'
// var url = 'http://www.imooc.com/learn/348'
var videoIds = [348, 259, 197, 134, 75 ]
//获取函数
function filterChapters(html) {
var $ = cheerio.load(html)
var chapters = $('.chapter')
var title = $('#page_headr .path span').text().trim()
var number = parseInt($($('.info_num i')[0]).text().trim(),10)
var courseData = {
title: title,
number: number,
videos: []
}
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.each(function (item) {
var video = $(this).find('.J-media-item')
var videoTitle = video.text()
var id = video.attr('href')
chapterData.videos.push({
title: videoTitle,
id: id
})
})
courseData.videos.push(chapterData)
})
return courseData
}
//打印函数
function printCourseInfo(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) {
var chapterTitle = item.chapterTitle
console.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
})
//请求完成,通过resolve将获取的值传递下去
res.on('end', function () {
resolve(html)
// var courseData = filterChapters(html)
// printCourseInfo(courseData)
})
//请求出错,传出错误信息
}).on('error', function (e) {
reject(e)
console.log('出错')
})
})
};
var fetchCourseArray = []
//遍历获取课程的id函数,返回一个promise数组
videoIds.forEach(function (id) {
//将方法push到数组里,函数返回的是Promise对象
fetchCourseArray.push(getPageAsync(baseUrl + id))
//baseUrl + id 就是url地址
})
Promise
//all方法接收一个参数,里面是多个promise对象
.all(fetchCourseArray)
.then(function (pages) {
var coursesData = []
pages.forEach(function(html) {
var courses = filterChapters(html)
coursesData.push(courses)
})
//number从大到小排列
coursesData.sort(function(a, b) {
return a.number < b.number
})
printCourseInfo(coursesData)
})