You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何整理从NBA数据网站爬取的字符串文本,实现数据结构化处理?

解决方案

你当前的问题出在直接调用了.text()方法,它会把所有选中行的文本内容直接拼接成单一字符串,完全丢失了原有的表格结构。要生成结构化数据,需要遍历每一行球员数据,逐个提取字段:

const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs');
const url = 'https://www.basketball-reference.com/leagues/NBA_2023_per_game.html';

axios(url)
  .then(response => {
    const html = response.data;
    const $ = cheerio.load(html);
    const playersData = [];

    // 遍历每一行球员数据
    $('.full_table').each((index, element) => {
      const playerRow = $(element);
      // 提取姓名
      const playerName = playerRow.find('td[data-stat="player"]').text().trim();
      // 提取各项统计数据
      const stats = {
        team: playerRow.find('td[data-stat="team_id"]').text().trim(),
        position: playerRow.find('td[data-stat="pos"]').text().trim(),
        gamesPlayed: playerRow.find('td[data-stat="g"]').text().trim(),
        pointsPerGame: playerRow.find('td[data-stat="pts"]').text().trim(),
        reboundsPerGame: playerRow.find('td[data-stat="trb"]').text().trim(),
        assistsPerGame: playerRow.find('td[data-stat="ast"]').text().trim(),
        // 可根据需求添加更多字段,参考页面td的data-stat属性即可
      };

      playersData.push({
        name: playerName,
        statistics: stats
      });
    });

    // 打印结构化数据
    console.log(playersData);
    // 保存为JSON文件方便后续操作
    fs.writeFileSync('nba_2023_per_game.json', JSON.stringify(playersData, null, 2));
  })
  .catch(console.error);

关键说明:

  • 用.each()遍历每一行球员数据,确保每条数据独立处理,不会混在一起
  • 通过td元素的data-stat属性精准提取对应统计项,避免因页面结构微调导致提取错误
  • 最终生成的数组中,每个元素都是包含name(姓名)和statistics(统计数据)的对象,完全符合你需要的结构化形式
  • 额外添加了保存JSON文件的逻辑,方便后续直接调用数据

内容的提问来源于stack exchange,提问作者superman1000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 23:07:35