nodejs ---- commencer

Suivez le MOOC pour éliminer une vague d'utilisation de nodejs pour explorer le réseau MOOC

Ne dis pas de bêtises, passe directement au code, il est trop tard. Le tutoriel d'installation et cette note seront ajoutés demain.
Explorez cette page: https://www.imooc.com/learn/348
Créez-en un: crawler.js

var http = require("https")
var cheerio = require("cheerio")
var url = "https://www.imooc.com/learn/348"

function filterChapters(html){
    var $ = cheerio.load(html)
    var chapters = $(".chapter")

    var courseData = []

    chapters.each(function (item) {
        var chapter = $(this)
        var chapterTitle = chapter.find("h3").text()
        var 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 + "\n")
        console.log(chapterTitle)

        item.videos.forEach(function (video) {
            // console.log(" 【" + video.id + "】 " + video.title +"\n")
            console.log("【" + video.id + "】" + video.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("获取失败!")
})

résultat de l'opération:
Insérez la description de l'image ici

Au revoir bonne nuit!

Je suppose que tu aimes

Origine blog.csdn.net/qq_38637558/article/details/83480417
conseillé
Classement