const http = require('http'); const url = 'http://www.imooc.com/learn/348'; const cheerio = require('cheerio'); function filterChapters(html){ let $ = cheerio.load(html); let chapters = $('.chapter'); //创建一个储存章节的数组 let cunChapters = []; //遍历章节 chapters.each(item=>{ let chapter = $(this); let chapterTitle = chapter.find('strong').text(); let chapterVideo = chapter.find('.video').children('li'); // console.log(chapterTitle); //单个包含视频和章节标题的章节 let chapterData = { chapterTitle: chapterTitle, chapterVideo: [] } chapterVideo.each(vItem=>{ let video = $(this).find('.J-media-item'); let videoTitle = video.text(); let videoId = video.attr('href').split('video/')[1]; // console.log(videoTitle); //单个包含视频标题和视频id的video chapterData.chapterVideo.push({ videoTitle: videoTitle, videoId: videoId }) }) cunChapters.push(chapterData);//单个章节的集合 }); return cunChapters; }; //打印结果 function viewHtml(cunChapters){ cunChapters.forEach(item=>{ //打印章节标题 let chapterTitle = item.chapterTitle; console.log(chapterTitle + '\n'); //打印视频 item.chapterVideo.forEach(vItem=>{ // let videoTitle = vItem.videoTitle; // let id = vItem.videoId; //打印video标题 console.log('【'+ vItem.videoId + '】' + vItem.videoTitle + '\n'); }) }) } http.get(url,function (res){ let html =''; res.on('data',function(data){ html += data; }); res.on('end',()=>{ let cunChapters = filterChapters(html); viewHtml(cunChapters); }) }).on('error',e=>{ console.log('错误'); })
找了一晚上
相关分类