javascript - Axios & Cheerio - 不能选择多个表格行
问题描述
一直在玩 axios 和 Cheerio。我试图从世界橄榄球排名网站上抓取表格数据。我想返回表格的前 10 行。 https://www.world.rugby/tournaments/rankings/mru
目前我只能检索表格的第一行,我不知道为什么。
const axios = require('axios')
const cheerio = require('cheerio')
async function getWorldRankings() {
try {
const siteUrl = 'https://www.world.rugby/tournaments/rankings/mru'
const { data } = await axios({
method: "GET",
url: siteUrl,
})
const $ = cheerio.load(data)
const elemSelector = 'body > section > div.pageContent.flex-content > div:nth-child(2) > div.column.large-8 > div > section > section > div.fullRankingsContainer.large-7.columns > div > div > table > tbody > tr'
$(elemSelector).each((parentIndex, parentElem) => {
$(parentElem).children().each((childIndex, childElem) => {
console.log($(childElem).text());
})
})
} catch (err) {
console.error(err);
}
}
getWorldRankings()
结果:
>node index.jsx
Position
Teams
Points
对于完整的上下文和信用,我正在使用本指南: https ://www.youtube.com/watch?v=5YCuUCRS_Ks (我使用相同的代码只是不同的 url 和 css 选择器 - 我可以检索表行作为打算用他的例子 coinmarketcap.com 和许多其他网站)。
对于世界橄榄球排名网站 - 即使 html 在开发工具中可用,是否以某种方式注入的数据使其无法选择?(我不知道我在说什么只是猜测)。
谢谢你的帮助。
节点 v16.4.2 “axios”:“^0.22.0”,“cheerio”:“^1.0.0-rc.10”,
解决方案
该表的数据稍后会使用 AJAX 加载,并且最初并未与页面一起加载,因此您无法使用 Cheerio 选择它。好消息是你甚至不需要 Cheerio。如果您查看浏览器开发工具中的网络请求选项卡,您会看到发出的 AJAX 请求使用以下 URL 将 JSON 格式的数据(您想要的数据)加载到页面中:
https://cmsapi.pulselive.com/rugby/rankings/mru?language=en&client=pulse
推荐阅读
- php - 使用 select2 时,选择框自动隐藏
- php - Doctrine - 将唯一条目映射到多个表
- azure - 在 Azure Devops 中运行 Canopy
- compiler-errors - 用于在 Verilog 中打包和解包 3-D 数组的宏
- node.js - Mongoose:有没有办法通过使用单个 mongoose 更新操作来实现这个功能?
- visual-studio - 如何在没有 Visual Studio 的情况下使用 PVS-Studio 运行 .NET Core 项目?
- python - 决策树分类器如何处理全局约束?
- ios - 在 Swift 4 中使用 NSSetUncaughtExceptionHandler
- laravel - 查询生成器中的未定义变量
- spring-boot - Spring boot - Apache 反向代理背后的 Spring 安全性