You need to enable JavaScript to run this app. Python爬取Transfermarkt多页URL脚本报AttributeError异常求助
优惠活动
大模型
产品
解决方案
定价
更多

Python爬取Transfermarkt多页URL脚本报AttributeError异常求助

报错原因拆解
  • 代码执行soup.find_all('table', class_ = 'items')时,返回的是匹配元素组成的ResultSet列表,并非单个可调用.find()方法的DOM节点,直接对列表调用find方法就会触发目标AttributeError。
  • 链接提取逻辑完全错位:spielprofil_tooltip是玩家详情链接<a>标签上的class属性,不是表格节点的子层级,直接遍历表格对象根本拿不到有效链接。
  • 页码参数完全失效:extract()函数内部把请求URL的页码写死为page/1,循环时传入的页码变量没有参与URL拼接,哪怕循环9次,实际只会重复请求第1页内容。
  • 遍历顺序逻辑颠倒:拿到链接元素集合后,才需要遍历单个元素提取href属性,原代码先对集合做无效的find调用,再遍历返回的结果集,流程完全走不通。
修正后可运行代码
import requests
from bs4 import BeautifulSoup
import pandas as pd

def extract(page):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'}
    # 拼接动态页码,避免写死单页地址
    url = f'https://www.transfermarkt.com/detailsuche/spielerdetail/suche/27403221/page/{page}'
    # 增加超时参数,避免请求卡死
    r = requests.get(url, headers, timeout=10)
    soup = BeautifulSoup(r.content, 'html.parser')
    return soup

def trasform(soup, urllist):
    # 定位单个结果表格,而非find_all返回的元素列表
    result_table = soup.find('table', class_='items')
    if not result_table:
        return
    # 在表格范围内定位所有带目标class的链接节点
    link_tags = result_table.find_all('a', class_='spielprofil_tooltip')
    for item in link_tags:
        href = item.attrs.get('href')
        if not href:
            continue
        full_url = 'https://www.transfermarkt.com' + href
        # 简单去重,避免重复收录同个URL
        if not any(exist['url'] == full_url for exist in urllist):
            urllist.append({'url': full_url})

if __name__ == "__main__":
    urllist = []
    for i in range(1, 10):
        print(f'Getting page, {i}')
        page_soup = extract(i)
        trasform(page_soup, urllist)

    df = pd.DataFrame(urllist)
    print(df.head())
    df.to_csv('urlslist.csv', index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 22:36:01