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

如何编写Python程序获取ESPN网站指定NBA球队的RPI值?

解决动态类名的NBA球队RPI获取问题

Got it, let's figure out how to pull the RPI value for a given NBA team without getting stuck on those dynamic row classes. The core idea here is to completely ignore the odd/even row labels and instead target the team name directly in each table row, then grab the corresponding RPI from that same row.

解决方案步骤

  • 用requests获取页面内容,带上浏览器模拟的请求头避免被网站拦截
  • 用BeautifulSoup解析HTML结构,跳过依赖动态类名的定位方式
  • 遍历所有数据行,提取每行的球队名称并和用户输入做不区分大小写的匹配
  • 找到匹配行后,提取对应的RPI值返回

完整代码示例

import requests
from bs4 import BeautifulSoup

def get_nba_rpi(team_name):
    # 模拟浏览器请求头,防止被网站拦截
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
    }
    rpi_url = 'http://www.espn.com/nba/stats/rpi'
    
    try:
        # 发送请求并检查是否成功
        response = requests.get(rpi_url, headers=headers)
        response.raise_for_status()
        
        # 解析页面HTML
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 定位RPI数据表格(根据页面实际结构调整选择器)
        rpi_table = soup.find('table', class_='Table')
        if not rpi_table:
            return "无法找到RPI数据表格,请检查页面结构是否更新"
        
        # 遍历所有数据行,跳过表头行
        for row in rpi_table.find_all('tr')[1:]:
            # 提取当前行的球队名称(根据页面实际标签调整)
            team_element = row.find('a', class_='AnchorLink')
            if not team_element:
                continue
            
            current_team = team_element.get_text(strip=True)
            # 不区分大小写匹配球队名称
            if current_team.lower() == team_name.lower():
                # 提取RPI值(根据页面列顺序调整索引,这里假设RPI在第4列)
                rpi_value = row.find_all('td')[3].get_text(strip=True)
                return f"{current_team}的RPI值为: {rpi_value}"
        
        # 未找到对应球队时返回提示
        return f"未找到球队「{team_name}」,请检查名称是否正确"
    
    except requests.exceptions.RequestException as e:
        return f"请求过程出错: {str(e)}"

# 测试功能
if __name__ == "__main__":
    input_team = input("请输入NBA球队名称: ")
    print(get_nba_rpi(input_team))

关键细节说明

  1. 彻底避开动态类名:我们没有依赖oddrow/evenrow或带随机ID的类名,而是直接通过球队名称匹配行,完全不受行位置、奇偶性变化的影响。
  2. 容错性处理:加入了请求异常捕获、表格/球队未找到的提示,让程序更健壮。
  3. 适配页面变化:如果之后页面结构更新,你只需要调整team_element和rpi_value的选择器(可以通过浏览器开发者工具查看页面源码确认位置)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:41:52