我正在运行以下代码来抓取数据。然而,代码只抓取第一个元素。
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 =>
[...$(e).find("td")]
.flatMap((e, i) =>
i === 1
? [$(e).find("a").attr("href"), $(e).text()]
: $(e).text()
)
.slice(1, -1)
);
console.log(data);
})
.catch(err => console.error(err));