初學nodejs---http小爬蟲

來源:互聯網
上載者:User

標籤:

 1 //HTTP小爬蟲 2 //×××××類似 $.AJAX×××××× 3  4  5 var http = require(‘http‘); //載入http模組 6  7 var cheerio = require(‘cheerio‘);//載入第三方模組 cheerio 類似JQuery 8  9 // 安裝方法 npm install cheerio10 11 12 function printCourseInfo(courseData) {//列印函數 傳入擷取資料13     courseData.forEach(function(item) {//迴圈列印14         var chapterTitle = item.chapterTitle;15 16         console.log(chapterTitle + ‘\n‘);17 18         item.videos.forEach(function(video) {19             console.log(‘[‘ + video.id + ‘]‘ + video.title + ‘\n‘);20         })21     })22 }23 24 25 function fliterChapters(html) {//資料篩選函數26 27     var $ = cheerio.load(html);28 29     var chapters = $(‘.chapter‘)//擷取元素30 31 32 //目標資料結構33     /*    [{34             capterTitle:‘‘,35             videos:‘‘,36             id:‘‘37         }]*/38 39     var courseData = [];//存放數組40 41 42     chapters.each(function(item) {43         var chapters = $(this);44 45         var chapterTitle = chapters.find(‘strong‘).text();46 47 48         var videos = chapters.find(‘.video‘).children(‘li‘);49 50         var chapterData = {51             chapterTitle: chapterTitle,52             videos: []53         }54 55         videos.each(function(item) {56             var video = $(this).find(‘.J-media-item‘);57             var videoTitle = video.text();58             var id = video.attr(‘href‘).split(‘video/‘)[1]59 60 61             chapterData.videos.push({62                 title: videoTitle,63                 id: id64             })65         })66 67 68         courseData.push(chapterData);69     })70 71     return courseData//資料拼接完成並返回72 73 }74 75 //目標url76 var url = ‘http://www.imooc.com/learn/348‘;//慕課網77 78 79 80 //使用get方法81 http.get(url, function(res) {//get方法爬取代碼82     var html = ‘‘;83 84     res.on(‘data‘, function(data) {//擷取資料事件85         html += data;86     })87 88     res.on(‘end‘, function() {//擷取結束事件89         var courseData = fliterChapters(html);90 91         printCourseInfo(courseData);92     })93 94 }).on(‘error‘, function() {95     console.log(‘擷取錯誤!‘);//報錯96 })

 

初學nodejs---http小爬蟲

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.