前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用node.js抓取其他网站数据,以及cheerio的介绍

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

作者头像
_kyle
发布2020-08-24 12:44:13
2.2K0
发布2020-08-24 12:44:13
举报
文章被收录于专栏:kyle的专栏kyle的专栏kyle的专栏

一、基本思路

  首先寻找一个网址: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("成功")
        });
    })
});
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、基本思路
  • 二、学习网址
  • 二、什么是cheerio以及如何使用
  • 三、具体代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档