const http = require('http');const cheerio = require('cheerio');const url = "http://www.imooc.com/learn/348";http.get(url, (res) => { var html = ""; res.on('data', (data) => { html += data; }); res.on('end', () => { var courseData = filterChapters(html); printCourseData(courseData); })}).on('error', () => { console.log("获取数据出错!");});function filterChapters(html) { // [ // { // "chapterTitle": "", // video: { // title: "", // id: "" // } // } // ] var $ = cheerio.load(html); var chapters = $('.chapter'); var courseData = []; chapters.each((index, item) => { var chapter = $(this); var chapterTitle = chapter.find("strong").text(); console.log(chapterTitle); var videos = chapter.find('ul').children("li"); var chapterData = { chapterTitle: chapterTitle, videos: [] } videos.each((item) => { var video = $(this).find(".J-media-item"); var videoTitle = video.find(".icon-video").text(); var id = videos.attr("href").split("video/")[1]; chapterData.video.push({ "title": videoTitle, "id": id }); }); courseData.push(chapterData); }); return courseData;}function printCourseData(courseData) { courseData.forEach(function (element) { var chapterTitle = element.chapterTitle; console.log(chapterTitle + '\n'); element.videos.forEach((video) => { console.log("【" + video.id + "】" + video.title + "\n"); }); }, this);}
- 1 回答
- 0 关注
- 1651 浏览
添加回答
举报
0/150
提交
取消