爬虫:把网页爬下来(发送http请求,保存返回的结果,一般是html),分析html拿到有用数据。
一、获取页面源码
拿到http://www.imooc.com/learn/348的源码【日期20170329】
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('获取课程数据出错');});
2、分析获取html中有用数据
先安装一个模块cheerio,cheerio可以理解成一个 Node.js 版的 jquery。
npm install cheerio
var http=require('http');var cheerio=require('cheerio');var url='http://www.imooc.com/learn/348';//分析用cheerio模块function filterChapters(html){ var $=cheerio.load(html); var chatpers=$('.chapter');//所有章节的数组/*//期望的数据结构 [{ chapterTitle:'', videos:[ title:'', id:'' ] }]*/ var courseData=[]; chatpers.each(function(item){ var chapter=$(this); var chapterTitle=chapter.find('strong').text(); videos=chapter.find('.video').children('li'); var chapterData={ chapterTitle:chapterTitle, videos:[] }; videos.each(function(item){ var video=$(this).find('.J-media-item'); var videoTitle=video.text(); var id=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(item){ console.log('【'+item.id+'】'+item.title+'\n'); }) })}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('获取课程数据出错');});
本文作者,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:有问题欢迎与我讨论,共同进步。