我正在运行以下代码来抓取数据。然而,代码只抓取第一个元素。
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"
// }
有什么建议我做错了什么吗?
您可以通过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
}))
got
和 jsonframe-cheerio
已弃用。避开他们。
以下是如何使用标准 fetch 和 Cheerio 代码执行此操作(fetch 是 Node 18+ 中原生的,cheerio 目前每周下载量为 7,870,278 次,因此它的受欢迎程度比 jsonframe-cheerio 的 12 周下载量高出 655,856 倍)。
const cheerio = require("cheerio"); // ^1.0.0-rc.12
const url = "<Your URL>";
fetch(url)
.then(res => {
if (!res.ok) {
throw Error(res.statusText);
}
return res.text();
})
.then(html => {
const $ = cheerio.load(html);
const data = [...$("table:last").find("tr:has(td)")].map(e => ({
coin: $(e).find("td:nth-child(2)").text(),
url: $(e).find("td:nth-child(2) a").attr("href"),
symbol: $(e).find("td:nth-child(3)").text(),
price: $(e).find("td:nth-child(5)").text(),
}));
console.log(data.slice(0, 20));
})
.catch(err => console.error(err));
输出:
[
{
coin: 'BTCBitcoin',
url: '/currencies/bitcoin/',
symbol: 'BTC',
price: '$70,271.61'
},
{
coin: 'ETHEthereum',
url: '/currencies/ethereum/',
symbol: 'ETH',
price: '$3,606.56'
},
{
// ...
请注意,在撰写本文时,价格会在前 20 个左右之后异步加载,因此,如果您需要这些详细信息,请考虑使用 Puppeteer 等浏览器自动化库,或考虑进行 API 调用。