NodeJs爬虫速成

mark一次Nodejs爬虫入门经历

需要用到的依赖

cheerio
superagent

cheerio是类似于jquery 操作dom获取数据
superagent则是请求对应的网址并返回网页dom数据
具体详情可以百度

npm init 初始化一个项目
新建一个Index.js
引入上述的依赖

const superagent = require('superagent');
const cheerio = require('cheerio');

引入fs文件管理

const fs = require('fs');

爬目标网址 例如微博热搜

const hot = `https://s.weibo.com/top/summary?cate=realtimehot`;

使用superagent请求微博热搜,会返回两个参数 第一个为error 请求失败的错误, 第二个是请求成功后网页的数据
在请求失败抛出错误

superagent.get(hot, (error, result) => {
  if(error){
    return new Error(error);
  }
}

请求成则使用cheerio处理dom元素

const $ = cheerio.load(result.text);
const list = [];// 存储数据


可以看出来都是比较规则的数据 用Jquery的each循环可以非常方便的取出数据来

  $('#pl_top_realtimehot table tbody tr').each(function (index) {
    if (index) {
      const $td = $(this).children().eq(1);
      const link = hot + $td.find("a").attr("href");
      const text = $td.find("a").text();
      const hotValue = $td.find("span").text();
      const icon = $td.find("img").attr("src")
        ? "https:" + $td.find("img").attr("src")
        : "";
      list.push({
        index,
        link,
        text,
        hotValue,
        icon,
      })
    }
  })

最后fs写入数据

  fs.writeFileSync(
    `${__dirname}/public/hotSearch.json`,
    JSON.stringify(list),
    "utf-8"
  )

…end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值