zoukankan      html  css  js  c++  java
  • nodejs爬虫

    爬虫:把网页爬下来(发送http请求,保存返回的结果,一般是html),分析html拿到有用数据。

    一、获取页面源码

    拿到http://www.imooc.com/learn/348的源码【日期20170329】

    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('获取课程数据出错');
    });

    2、分析获取html中有用数据

    先安装一个模块cheerio,cheerio可以理解成一个 Node.js 版的 jquery。

    npm install cheerio

    var http=require('http');
    var cheerio=require('cheerio');
    var url='http://www.imooc.com/learn/348';
    //分析用cheerio模块
    function filterChapters(html){
        var $=cheerio.load(html);
        var chatpers=$('.chapter');//所有章节的数组
    /*//期望的数据结构
        [{
            chapterTitle:'',
            videos:[
                title:'',
                id:''
            ]
        }]*/
        var courseData=[];
        chatpers.each(function(item){
            var chapter=$(this);
            var chapterTitle=chapter.find('strong').text();
            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+'
    ');
            item.videos.forEach(function(item){
                console.log('【'+item.id+'】'+item.title+'
    ');
            })
        })
    }
    
    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('获取课程数据出错');
    });

    本文作者starof,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:http://www.cnblogs.com/starof/p/6639505.html有问题欢迎与我讨论,共同进步。

  • 相关阅读:
    MongoDB的固定集合
    MongoDB的导入导出
    MongoDB的数据备份与恢复
    MongoDB的索引
    MongoDB简单CRUD场景
    MongoDB入门
    NOSQL概念入门
    Java静态代理和动态代理
    a=a+1背后的内存模型和CPU高速缓存
    SpringCloud的学习记录(6)
  • 原文地址:https://www.cnblogs.com/starof/p/6639505.html
Copyright © 2011-2022 走看看