命令行执行成功之后,每个详细的课程信息显示为undefined,求指教?
代码部分:
var http = require("http"); //加载http模块
var cheerio = require("cheerio"); //加载cheerio模块
var url = "http://www.imooc.com/learn/348";
// 获取课程数据
function filterChapters(html){
var $ = cheerio.load(html);
var chapters = $(".chapter");
/*
要获取的数据的结构
[{
chapterTitle: "",
videos: [
title: "",
id: ""
]
}]
*/
var courseData = [];
chapters.each(function(item){
var chapter = $(this);
var chapterTitle = chapter.find("strong").text().trim();
var videos = chapter.find(".video").children("li");
var chapterData = {
chapterTitle: chapterTitle,
videos: []
};
videos.each(function(item){
var video = $(this).find(".video");
var videoTitle = video.text();
var id = String(video.attr("href")).split("video/")[1];
chapterData.videos.push({
title: 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(video){
console.log(" 【 " + video.id + " 】 " + video.title + "\n");
});
});
};
// get方法发送请求
http.get(url, function(res){
var html = "";
res.on("data", function(data){
html += data;
});
res.on("end", function(){
var courseData = filterChapters(html);
printCourseInfo(courseData);
});
}).on("error", function(){ //监听错误处理
console.log("获取课程数据出错!");
});