您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页2018-10-23 node cheerio 简单爬虫(爱国主

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

结果


爱国主义好青年

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务