node.js基礎模組http、網頁分析工具cherrio實現爬蟲,node.jscherrio

來源:互聯網
上載者:User

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爬蟲進階教程之非同步並發控制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.