【问题标题】:Scraping all elements with cheerio用cheerio刮掉所有元素
【发布时间】:2017-10-30 10:03:57
【问题描述】:

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

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

async function scrapeCoinmarketCap() {
    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
    }))
}

scrapeCoinmarketCap()

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

任何建议我做错了什么?

感谢您的回复!

【问题讨论】:

  • 我不明白这样做的意义。如果您以常规方式抓取它,则可以在浏览器控制台中对其进行测试并对其进行调整,直到正确为止。

标签: javascript node.js cheerio


【解决方案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
}))

【讨论】:

    猜你喜欢
    • 2021-10-16
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2021-03-17
    • 1970-01-01
    • 2021-02-05
    • 2014-08-10
    相关资源
    最近更新 更多