搜索
node.js - 下面这段代码用在命令行node运行,没任何反映?看看有什么问题?
阿神
阿神 2017-04-17 12:03:51
[Node.js讨论组]
var http = require('http');
var cheerio = require('cheerio');
var url = 'http://www.imooc.com/learn/348';

function filterChapters(html) {
    var $ = cheerio.load(html);
    var chapter = $('.chapter');

    // [{
    //     chapterTitile: '',
    //     videos: [
    //         title: '',
    //         id: ''
    //     ]
    // }]

    var courseData = [];
    chapter.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('.studyvideo');
            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('获取数据出错!'); //捕捉错误
});
阿神
阿神

闭关修行中......

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号