2018-10-23 node cheerio 简单爬虫(爱国主义好青年)

安装 cheerio 插件

cnpm i cheerio -g/D

代码:

const http = require("http"),
    fs = require("fs"),
    cheerio = require("cheerio");

var url = "。。。。。。。。。。。。。。。。这里url自己换一下";
http.get(url,(res)=>{
    var html = "";
    res.on("data",(data)=>{
        html+=data; 
    })
    res.on("end",()=>{
        fs.writeFile("baidu.html",html,function(err){
            if(err){
                return ;
            }
            console.log("html保存成功")  
        })
        // console.log(html);
        const $ = cheerio.load(html);
   
        let buf = "";
        // console.log($);
        // console.log($("#main .contents p"))
        $("a").each(function(){  
            // console.log("66666")
            buf += $(this).text() + "\n"; 
        })
        // console.log(buf);   
        fs.appendFile("wenzi.txt",buf,(err)=>{
            if(err){ 
                console.log(err);
                return ;
            }
            console.log("保存文字成功!");
        });
    })
})

结果


2018-10-23 node cheerio 简单爬虫(爱国主义好青年)_第1张图片
爱国主义好青年

你可能感兴趣的:(2018-10-23 node cheerio 简单爬虫(爱国主义好青年))