2018-10-23 node cheerio 简单爬虫(爱国主

2018-10-23  本文已影响3人  不知道取个什么昵称不如娶个媳妇

安装 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("保存文字成功!");
        });
    })
})

结果


爱国主义好青年
上一篇 下一篇

猜你喜欢

热点阅读