var http=require('http')
var cheerio=require('cheerio')
var url = 'http://www.imooc.com/learn/348'
var filterChapter=function(data){
var $ = cheerio.load(data)
var chapters=$('.chapter')
var courseData = []
chapters.each(function(item){
var chapter=$(this)
chapterTitle=chapter.find("strong").text()
videos=chapter.find("li")
var chapterData={
chapterTitle:chapterTitle,
videos:[]
}
videos.each(function(item){
var video=$(this)
var videoTitle=video.find(".J-media-item").text()
var id = video.find(".J-media-item").attr("href").split("video/")[1]
chapterData.videos.push({
videoTitle:videoTitle,
id:id
})
})
courseData.push(chapterData)
})
return courseData
}
function printcourseinfo(courseData){
courseData.forEach(function(item){
var chapterTitle=item.chapterTitle
console.log(chapterTitle+'\n')
item.videos.forEach(function(it){
var videoTitle= it.videoTitle
var videoid=it.id
console.log(videoTitle+" "+videoid+"\n")
})
})
}
http.get(url,function(res){
var html = ''
res.on('data',function(data){
html += data
})
res.on('end',function(){
var courseData = filterChapter(html)
printcourseinfo(courseData)
})
}).on('error',function(){
console.log('获取课程数据')
})