node.js基礎模組http、網頁分析工具cherrio實現爬蟲,node.jscherrio
一、前言
說是爬蟲初探,其實並沒有用到爬蟲相關第三方類庫,主要用了node.js基礎模組http、網頁分析工具cherrio。 使用http直接擷取url路徑對應網頁資源,然後使用cherrio分析。 這裡我主要學習過的案例自己敲了一遍,加深理解。在coding的過程中,我第一次把jq擷取後的對象直接用forEach遍曆,直接報錯,是因為jq沒有對應的這個方法,只有js數組可以調用。
二、知識點
①:superagent抓去網頁工具。我暫時未用到。
②:cherrio 網頁分析工具,你可以理解其為服務端的jQuery,因為文法都一樣。
1、抓取整個網頁
2、分析後的資料,提供的樣本為案例實現的例子。
爬蟲初探源碼分析
var http=require('http');var cheerio=require('cheerio'); var url='http://www.imooc.com/learn/348'; /****************************列印得到的資料結構[{ chapterTitle:'', videos:[{ title:'', id:'' }]}]********************************/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'); }) });} /*************分析從網頁裡抓取到的資料**************/function filterChapter(html){ var courseData=[]; var $=cheerio.load(html); var chapters=$('.chapter'); chapters.each(function(item){ var chapter=$(this); var chapterTitle=chapter.find('strong').text(); //找到章區段標頭 var videos=chapter.find('.video').children('li'); var chapterData={ chapterTitle:chapterTitle, videos:[] }; videos.each(function(item){ var video=$(this).find('.studyvideo'); var title=video.text(); var id=video.attr('href').split('/video')[1]; chapterData.videos.push({ title:title, id:id }) }) courseData.push(chapterData); }); return courseData;} 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('擷取課程資料出錯');})
參考資料:
https://github.com/alsotang/node-lessons/tree/master/lesson3
http://www.imooc.com/video/7965
您可能感興趣的文章:
- NodeJS製作爬蟲全過程
- NodeJS製作爬蟲全過程(續)
- nodejs爬蟲抓取資料亂碼問題總結
- nodejs爬蟲抓取資料之編碼問題
- 基於Node.js的強大爬蟲 能直接發布抓取的文章哦
- Nodejs爬蟲進階教程之非同步並發控制