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有问题欢迎与我讨论,共同进步。

  • 相关阅读:
    注册表
    windows.location.href在IE6下停止工作
    LINUX配置IP的三种方式
    InnoSetup 打包代码 检测.netFramework
    SQLiteHelper
    黑马程序员_看视频记笔记_C#编程基础02
    通过注册表来检测是否安装Office
    SQLiteHelper
    TSQL
    IIS下发布关于Excel导入导出时遇到的问题集锦
  • 原文地址:https://www.cnblogs.com/starof/p/6639505.html
Copyright © 2011-2022 走看看