美文网首页
2018-10-23 node cheerio 简单爬虫(爱国主

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

作者: 不知道取个什么昵称不如娶个媳妇 | 来源:发表于2018-10-23 20:54 被阅读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("保存文字成功!");
        });
    })
})

结果


爱国主义好青年

相关文章

网友评论

      本文标题:2018-10-23 node cheerio 简单爬虫(爱国主

      本文链接:https://www.haomeiwen.com/subject/lthzzftx.html