美文网首页
5.Http小爬虫学习

5.Http小爬虫学习

作者: coderLfy | 来源:发表于2017-01-10 10:15 被阅读50次
    Http小爬虫学习

    Scott老师讲解的东西尤其是源码讲解我认为要先会用在进行深究

    Scott老师介绍
    cheerio这个工具 类似于jQuery

    安装方法:

    npm install cheerio

    1. Cheerio官方api 全英
    2. Node中文社区中的cheerio Api通读

    首先开启一个本地服务器测试一下

    // js代码
    var http = require('http');
    
    http
        .createServer(function(req, res){
          res.writeHead(200,{'Content-Type':'text/plain'});
          res.write('开始学习NodeJs好期待!');
          res.end();
        }).listen(8080);//端口号8080
    

    http://localhost:8080/ 服务地址

    贴代码:(慕课网Scott老师的进击NodeJs基础一)由于慕课改版了些,东西也改了,我自己稍微修改了一下可以使用

    var http = require('http');
    var cheerio = require('cheerio');//引入cheerio
    var url = 'http://www.imooc.com/learn/348';
    
    
    //按照格式存放数据
    function filterChapters(html){
      var $ = cheerio.load(html);//变成jq模样便于理解
      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(){
          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){//data事件
        html += data;
      });
      res.on('end',function(){//end 事件
        // console.log(html);
        var courseData = filterChapters(html);
        printCourseInfo(courseData);
      });
    }).on('error',function(){//error
      console.log('获取课程数据失败!');
    });
    
    

    相关文章

      网友评论

          本文标题:5.Http小爬虫学习

          本文链接:https://www.haomeiwen.com/subject/fbchbttx.html