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

Python网页爬取求助:BeautifulSoup获取UCI积分时class匹配异常

问题分析与解决

1. 类名匹配错误原因

你在搜索class_="cu600 "时末尾多了空格,BeautifulSoup会精确匹配类名字符串,但网页中不存在类名正好是cu600 (带空格)的元素,所以返回None。

而搜索class_="cu600"时,会匹配所有包含cu600类的元素(不管该元素是否还有其他类,比如gc cu600就是同时拥有gc和cu600两个类的元素),所以会得到结果,但这个结果大概率不是你要的赛事积分(而是总积分或其他统计数据)。

2. 修正代码获取最近赛事的UCI积分

要获取最近一场赛事的UCI积分,需要先定位到车手的赛事结果表格,再取第一行数据对应的积分列:

import requests
from bs4 import BeautifulSoup

# 请求页面
page = requests.get("https://www.procyclingstats.com/rider/tadej-pogacar")
soup = BeautifulSoup(page.text, "lxml")

# 定位赛事结果表格(表头包含赛事数据的目标表格)
results_table = soup.find("table", class_="results table")
if not results_table:
    print("未找到赛事结果表格")
else:
    # 获取表格的所有数据行(跳过表头,数据行类为row1/row2)
    data_rows = results_table.find_all("tr", class_=["row1", "row2"])
    if data_rows:
        # 取第一行(对应最近的赛事)
        latest_race_row = data_rows[0]
        # 提取该行的UCI积分、日期和赛事名称
        uci_points = latest_race_row.find("td", class_="cu600").text.strip()
        race_date = latest_race_row.find("td", class_="hidden-xs").text.strip()
        race_name = latest_race_row.find("td", class_="race").text.strip()
        
        print(f"最近赛事:{race_date} {race_name}")
        print(f"UCI积分:{uci_points}")
    else:
        print("未找到赛事数据")

代码说明

  • 通过class_="results table"精准定位赛事结果表格,避免误抓其他带cu600类的无关元素;
  • 数据行的类固定为row1或row2,取第一个数据行就是时间最近的赛事;
  • 用strip()去除文本中的多余空格和换行,保证输出结果整洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 03:42:15