Nodejs小爬蟲

來源:互聯網
上載者:User

標籤:ref   開啟   get   print   learn   原理   console   push   網站   

記得先裝載http這個模組

開啟cmd  :npm install http -g

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(‘擷取出錯‘)})

  

cmd:node一下,出來網頁源碼

 

然後npm install cheerio -g

用慕課網做測試哈哈哈  ,這裡要說明一點:代碼和課程中是不一樣的,因為網站改動了原始碼,class之類的名字換掉了,所以之前的爬蟲爬不出來的。還好知道原理以後自己去改就可以了。

/** * Created by Amy on 2017/7/13. */var http= require(‘http‘)var cheerio= require(‘cheerio‘)//先裝載這個模組var url=‘http://www.imooc.com/learn/348‘function filterChapters(html){    var $=cheerio.load(html)    var chapters= $(‘.chapter‘)    // [{    //     chapterTitle:‘‘,    //     videos:[    //         title:‘‘,    //          id:‘‘    //     ]    // }]    var courseData=[]    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(‘.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(video){            console.log(‘[‘+video.id+‘]‘+video.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(‘擷取出錯‘)})

  去node一下試試,好神奇吧。

 

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.