首页 > 解决方案 > 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”,

标签: javascriptnode.jsaxioscheerio

解决方案


该表的数据稍后会使用 AJAX 加载,并且最初并未与页面一起加载,因此您无法使用 Cheerio 选择它。好消息是你甚至不需要 Cheerio。如果您查看浏览器开发工具中的网络请求选项卡,您会看到发出的 AJAX 请求使用以下 URL 将 JSON 格式的数据(您想要的数据)加载到页面中:

https://cmsapi.pulselive.com/rugby/rankings/mru?language=en&client=pulse


推荐阅读