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

Python网页抓取:如何获取运动员Competitor字段的href链接?

爬取世界田径榜单时获取运动员Href链接的方法

原代码依赖pandas.read_html()只能提取表格的文本数据,无法获取运动员名称对应的Href链接。要实现这个需求,需要结合requests请求页面、BeautifulSoup解析HTML,同时提取表格数据和运动员链接,具体修改如下:

修改后的完整代码

import pandas as pd
import requests
from bs4 import BeautifulSoup

F, L = 1, 2  # 起始页和结束页
base_url = 'https://www.worldathletics.org'
all_data = []

for page in range(F, L+1):
    # 构造请求URL
    url = f'https://www.worldathletics.org/records/all-time-toplists/middle-long/one-mile/indoor/men/senior?regionType=world&page={page}&bestResultsOnly=false&oversizedTrack=regular&firstDay=1899-12-31&lastDay=2023-02-17'
    # 请求页面
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 找到目标榜单表格
    table = soup.find('table', class_='records-table')
    if not table:
        continue
    
    # 获取表头并新增运动员链接字段
    headers = [th.get_text(strip=True) for th in table.find('thead').find_all('th')]
    headers.insert(1, 'Athlete_Href')
    
    # 遍历表格行提取数据
    for row in table.find('tbody').find_all('tr'):
        cols = row.find_all('td')
        row_data = [col.get_text(strip=True) for col in cols]
        # 提取运动员的Href链接并拼接完整地址
        athlete_link = cols[1].find('a')['href']
        full_link = base_url + athlete_link
        row_data.insert(1, full_link)
        
        all_data.append(row_data)

# 转换为DataFrame并添加自定义字段
df = pd.DataFrame(all_data, columns=headers)
df.insert(2, "Year", "AT")
df.insert(3, "Ind_Out", "I")
df.insert(4, "Gender", "M")
df.insert(5, "Event", "MILLA")
df.insert(6, "L_N", "L")

# 保存为CSV文件
df.to_csv('WA_AT_I_M_MILLA_L.csv', index=False)

关键逻辑说明

  • 改用requests获取页面原始HTML,确保能拿到所有页面元素,而非仅表格文本
  • 通过BeautifulSoup定位榜单表格,逐行提取数据时,从Competitor列的<a>标签中抓取href属性
  • 可根据需求调整链接存储形式:既可以保存完整的运动员页面链接,也可以从链接中截取运动员编码(比如从/athletes/united-states/123456中提取123456)
  • 保持原代码中自定义字段的插入逻辑,最终合并数据并导出为CSV

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:57:19