localhost:2015 端口var http = require('http')http .createServer(function(req, res){ res.writeHead(200, {'Content-Type':'text/plain'}) res.write('hello nodejs') res.end() }) .listen(2015)// 获取网页html// var http = require('http')// var url = 'http://www.imooc.com/learn/348'// http.get(url, function(res){// var html = ''// res.on('data',function(data){// html += data// })// res.on('end',function(){// console.log(html)// })// }).on('error', function(){// console.log('获取课程数据出错!')// })//获取页面的指定内容//当前目录安装cheerio --> npm install cheeriovar http = require('http')var cheerio = require('cheerio') //引用文件cheerio.jsvar url = 'http://www.imooc.com/learn/348'function filterChapters(html){ var $ = cheerio.load(html) var chapters = $('.learnchapter') //通过class learnchapter / chapter 拿到每个大章节 var courseData = [] chapters.each(function(item){ //遍历chapters里面的内容 var chapter = $(this) var chapterTitle = chapter.find('strong').text() //找到章节里面的strong标签内的内容 var videos = chapter.find('.video').children('li') //小章节内的li var childrenData = { //创建对象自变量 chapterTitle: chapterTitle, videos: [] //空数组 } videos.each(function(item){ var video = $(this).find('.studyvideo') //视频class var videoTitle = video.text() var id = video.attr('href').split('video/')[1] childrenData.videos.push({ title: videoTitle, id: id }) }) courseData.push(childrenData) }) return courseData}function printCourseInfo(courseData){ courseData.forEach(function(item){ var chapterTitle = item.chapterTitle console.log(chapterTitle + 'n') //打印标题 item.videos.forEach(function(video){ console.log(' 【' + video.id + '】' + video.title + '\n') }) })}http.get(url, function(res){ var html = '' res.on('data',function(data){ html += data }) res.on('end',function(){ // console.log(html) var courseData = filterChapters(html) printCourseInfo(courseData) })}).on('error', function(){ console.log('获取课程数据出错!')})