【问题标题】:Axios & Cheerio - can't select more than one table rowAxios 和 Cheerio - 不能选择多个表格行
【发布时间】:2021-10-04 08:07:50
【问题描述】:

刚刚玩过 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",

【问题讨论】:

    标签: javascript node.js axios cheerio


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-18
      • 2015-12-15
      • 1970-01-01
      • 2023-04-04
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      相关资源
      最近更新 更多