用cheerio刮掉所有元素

时间:2017-10-30 10:03:58

标签: javascript node.js cheerio

我正在运行以下代码来废弃数据。但是,代码只会废弃第一个元素。

const cheerio = require('cheerio')
const jsonframe = require('jsonframe-cheerio')
const got = require('got');

async function scrapCoinmarketCap() {
    const url = 'https://coinmarketcap.com/all/views/all/'
    const html = await got(url)
    const $ = cheerio.load(html.body)

    jsonframe($) // initializing the plugin

    let frame = {
        "Coin": "td.no-wrap.currency-name > a",
        "url": "td.no-wrap.currency-name > a @ href",
        "Symbol": "td.text-left.col-symbol",
        "Price": "td:nth-child(5) > a",
    }

    console.log($('body').scrape(frame, {
        string: true
    }))
}

scrapCoinmarketCap()

//Output -> only the first element
//    {
//      "Coin": "Bitcoin",
//      "url": "/currencies/bitcoin/",
//      "Symbol": "BTC",
//      "Price": "$6122.67"
//    }

有什么建议我做错了吗?

谢谢您的回复!

1 个答案:

答案 0 :(得分:1)

您可以使用List / Array模式获取所有货币数据:

let frame = {
  currency: {
    _s: "tr",
    _d: [{
      "Coin": "td.no-wrap.currency-name > a",
      "url": "td.no-wrap.currency-name > a @ href",
      "Symbol": "td.text-left.col-symbol",
      "Price": "td:nth-child(5) > a"
    }]
  }
}

console.log($('body').scrape(frame, {
  string: true
}))
相关问题