美文网首页
使用node.js抓取其他网站数据,以及cheerio的介绍

使用node.js抓取其他网站数据,以及cheerio的介绍

作者: 422ccfa02512 | 来源:发表于2018-09-18 23:10 被阅读99次

一、基本思路

   首先寻找一个网址:http://tech.ifeng.com/,因为这个是http协议,所以我们需要用到node.js的HTTP模块,我们使用HTTP模块中的get()方法进行抓取。其中假如我们不需要抓取的所有数据,而我们只需要其中的部分数据,比如某个类下面的a标签里的文字,这时如果是在前端中我们可以用DOM操作找到这个节点,但是node.js中没有DOM操作,所以这里我们需要用到cheerio这个库。既然抓取了网站上的数据就会涉及到文件的写入,这时需要用到node.js中的fs模块。

二、学习网址

https://cheerio.js.org/ cheerio官方学习文档
https://www.npmjs.com/package/cheerio cheerio npm网址
https://nodejs.org/dist/latest-v10.x/docs/api/ node.js官方文档
http://nodejs.cn/api/ node.js中文文档

二、什么是cheerio以及如何使用

   cheerio是专为服务器设计的核心jQuery的快速,灵活和精益实现。他可以像jquery一样操作字符串。

安装cheerio

npm install cheerio

具体使用

const cheerio = require('cheerio')
const $ = cheerio.load('<h2 class="title">Hello world</h2>')

$('h2.title').text('Hello there!')
$('h2').addClass('welcome')

$.html()
//=> <h2 class="title welcome">Hello there!</h2>

三、具体代码

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

http.get("http://tech.ifeng.com/", function(res) {
    // 设置编码
    res.setEncoding("utf8");
    // 当接收到数据时,会触发 "data" 事件的执行
    let html = "";
    res.on("data", function(data){
        html += data;
    });
    // 数据接收完毕,会触发 "end" 事件的执行
    res.on("end", function(){
        // 待保存到文件中的字符串
        let fileData = "";
        // 调用 cheerio.load() 方法,生成一个类似于 jQuery 的对象
        const $ = cheerio.load(html);
        // 接下来像使用 jQuery 一样来使用 cheerio
        $(".pictxt02").each(function(index, element) {
            const el = $(element);
            let link = el.find("h3 a").attr("href"),
                title = el.find("h3 a").text(),
                desc = el.children("p").text();

            fileData += `${link}\r\n${title}\r\n\t${desc}\r\n\r\n`;
        });

        // console.log("读取结束,内容:");
        // console.log(html);
        fs.writeFile("./dist/source.txt", fileData, function(err) {
            if (err)
                return;
            console.log("成功")
        });
    })
});

相关文章

网友评论

      本文标题:使用node.js抓取其他网站数据,以及cheerio的介绍

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