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

如何抓取Transfermarkt动态info-table数据并转为DataFrame?

解决方法

针对Transfermarkt页面中info-table模块的非固定行数据抓取,核心是通过行标签文本匹配对应值,而非依赖位置索引。以下是具体实现步骤:

1. 准备依赖库与反爬配置

使用requests请求页面,BeautifulSoup解析HTML,pandas处理数据。由于Transfermarkt有反爬机制,需添加请求头模拟浏览器:

import requests
from bs4 import BeautifulSoup
import pandas as pd
import time

# 模拟浏览器请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}

2. 定义单页面数据抓取函数

编写函数处理单个URL,提取info-table内的所有键值对:

def extract_info_table(url):
    # 延迟请求,避免触发反爬
    time.sleep(1)
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 定位info-table模块
    info_table = soup.find('div', class_='info-table')
    if not info_table:
        return {}
    
    # 遍历所有行,提取标签与对应值
    data = {}
    rows = info_table.find_all('div', class_='info-table__row')
    for row in rows:
        # 获取标签文本(加粗的span)
        label = row.find('span', class_='info-table__content--bold').get_text(strip=True)
        # 获取对应值文本
        value = row.find('span', class_='info-table__content').get_text(strip=True)
        data[label] = value
    
    return data

3. 批量处理URL DataFrame

遍历原DataFrame中的URL列,收集所有页面数据并转换为新的DataFrame:

# 假设原DataFrame名为url_df,包含列'url'
url_df = pd.DataFrame({'url': ['https://www.transfermarkt.com/ederson/profil/spieler/238223', ...]})

# 批量抓取数据
results = []
for idx, row in url_df.iterrows():
    url = row['url']
    print(f'正在处理: {url}')
    info_data = extract_info_table(url)
    # 保留原URL以便关联
    info_data['url'] = url
    results.append(info_data)

# 转换为最终DataFrame
final_df = pd.DataFrame(results)

关键说明

  • 按位置提取失败的原因:不同球员页面的info-table行顺序不固定(比如部分球员有"租借状态"行,部分没有),依赖索引位置会导致数据错位。
  • 反爬注意事项:添加time.sleep()控制请求频率,避免被网站封禁;若仍被限制,可考虑使用代理IP或会话保持。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:39:28