nodejs基础二

cheerio第三方的模块:cheerio是jquery核心功能的一个快速灵活而又简洁的实现,主要是为了用在服务器端需要对DOM进行操作的地方

用http模块做爬虫爬取网页的新闻:

const http =require("http");
const fs =require("fs");
const cheerio =require("cheerio");
http.get("http://news.baidu.com",(res)=>{
    var str ="";
    res.setEncoding("utf-8");//预防文字乱码问题
    res.on("data",(thunk)=>{
        str+=thunk;
    })
    res.on("end",()=>{
        var $ =cheerio.load(str);//将爬取的整个文档变成可操作的jQuery对象,就可以使用jQuery的方法了。
        fs.writeFileSync("./news.txt","","utf-8");
        $(".focuslistnews a").each((index,item)=>{
            fs.appendFileSync("./news.txt",$(item).text()+"\r\n","utf-8");
        })
    })
})

问题补充:path.join和path.resolve的区别?

path.join()方法是将多个参数字符串合并成一个路径字符串   console.log(path.join(__dirname,'a','b')); 假如当前文件的路径是E:/node/1,那么拼接出来就是E:/node/1/a/b。

path.resolve()方法可以将多个路径解析为一个规范化的绝对路径    path.resolve()方法是以程序为根目录,作为起点,根据参数解析出一个绝对路径

path.extname 取得当前文件的扩展名

__dirname 当前目录的绝对路径

__filename 当前文件的绝对路径

猜你喜欢

转载自www.cnblogs.com/dongdong1996/p/12089632.html