用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

相關文章
相關標籤/搜索