用Nodejs Cheerio爬取NPM包详细信息

前言

NodeJs是前端开发工程师最熟悉不过的了,下面我就介绍一下如何爬取npm官网的包数据。javascript

爬取数据

  1. init 一个package.json
npm init -y
复制代码
  1. 下载 cheeriorequestrequest-promise
npm install cheerio && npm install request && npm insatll request-promise
复制代码
  1. 新建一个 index.js文件,代码以下
const rp = require('request-promise');
    const cheerio = require('cheerio');
    
    const getNpmInfo = async ( packageName ) => {
    
      const options = {
        uri: 'https://www.npmjs.com/package/' + packageName,
        transform: body => cheerio.load(body)
      };
    
      const $ = await rp(options);
    
      let infoArray = [];
    
      $('._9dMXo ._2_OuR').each(function() {
        let key, value;
    
        // find 方法获取 key
        key = $(this).find('._1IKXc').text();
    
        // 下面两个 key 里面包含连接要单独处理
        if(key === 'repository' || key === 'homepage') {
          value = $(this).find('.n8Z-E').find('.zE7yA').attr('href');
        } else {
          value = $(this).find('.n8Z-E').text();
        }
    
        infoArray.push({key, value});
    
      })
    
      console.log(infoArray);
      // return infoArray;
    }
    
    getNpmInfo('webpack-dev-server');
    
    // module.exports = getNpmInfo;
复制代码
  1. 终端执行
node index.js
复制代码

会看到控制台以下图所示的内容前端

这样你就获取到了想要的信息了。

那么问题来了...java

Node环境获取的数据如何展现在浏览器环境里?node

我能想到的办法就是启一个服务去接收这个方法,而后返回查询到的值。webpack

启动服务

  1. 安装express
npm install express --save
复制代码
  1. index.js修改成以下,就是把这个方法暴露出去
const rp = require('request-promise');
    const cheerio = require('cheerio');
    
    const getNpmInfo = async ( packageName ) => {
      // ...
      // console.log(infoArray);
      return infoArray;
    }
    
    // getNpmInfo('webpack-dev-server');
    
    module.exports = getNpmInfo;
复制代码
  1. 新建 api.js,内容以下
const express = require('express');
    const getNpmInfo = require('./index');
    const PORT = 8803;
    const app = new express();
    
    app.use('/',  async function(req, res) {
      res.send (await getNpmInfo(req.query.name))
    })
    
    console.log('Serve is run at ' + PORT + ' !')
    
    app.listen(PORT);
复制代码
  1. 启动api.js
node api.js
复制代码
  1. 访问 localhost:8803/?name=webpack-dev-server 就能看到数据啦!

备注:固然若是想正式使用这个接口,那就要放在服务器上面。git

若是有什么好的方法能够解决数据可以在浏览器展现的问题,欢迎留言讨论。web

敬上 git 地址: get-npm-package-info 求个🌟,谢谢express

相关文章
相关标签/搜索