• 初学nodejs---http小爬虫


     1 //HTTP小爬虫
     2 //×××××类似 $.AJAX××××××
     3 
     4 
     5 var http = require('http'); //加载http模块
     6 
     7 var cheerio = require('cheerio');//加载第三方模块 cheerio 类似JQuery
     8 
     9 // 安装方法 npm install cheerio
    10 
    11 
    12 function printCourseInfo(courseData) {//打印函数 传入获取数据
    13     courseData.forEach(function(item) {//循环打印
    14         var chapterTitle = item.chapterTitle;
    15 
    16         console.log(chapterTitle + '
    ');
    17 
    18         item.videos.forEach(function(video) {
    19             console.log('[' + video.id + ']' + video.title + '
    ');
    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: id
    64             })
    65         })
    66 
    67 
    68         courseData.push(chapterData);
    69     })
    70 
    71     return courseData//数据拼接完成并返回
    72 
    73 }
    74 
    75 //目标url
    76 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 })
  • 相关阅读:
    Groovy新手教程
    cocos2d-x v3.2 FlappyBird 各个类对象详细代码分析(6)
    开机黑屏 仅仅显示鼠标 电脑黑屏 仅仅有鼠标 移动 [已成功解决]
    病毒木马查杀第002篇:熊猫烧香之手动查杀
    Activity具体解释(生命周期、以各种方式启动Activity、状态保存,全然退出等)
    白话经典算法系列之六 高速排序 高速搞定
    UVA580-Critical Mass
    FPGA 时序问题
    SVD神秘值分解
    Java中Integer类的方法
  • 原文地址:https://www.cnblogs.com/superZz/p/5874146.html
Copyright © 2020-2023  润新知