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

使用BeautifulSoup的Python网络爬虫仅返回一行数据且无法获取团队信息求助

问题排查与解决

问题1:仅输出最后一行数据

你定义的nick、team等变量在循环中会被每一行的数据反复覆盖,循环结束后自然只保留最后一次赋值的内容。而且你已经声明了player_list列表,但全程没有把爬取到的数据存入其中。

解决方式:

  • 在循环内将每行数据存入字典,再追加到player_list中
  • 循环结束后遍历列表输出所有数据,或在循环内直接打印单条数据

问题2:无法获取team数据

从截图对应的HLTV页面结构来看,team列的文本内容嵌套在<span>标签里(外层是<a>和<img>),直接取td[1].text只能拿到空白或无效内容。需要精准定位到<span>标签再提取文本。

另外你的代码存在缩进问题:第二个for row in rows:循环应该嵌套在第一个for player_data...循环内,否则逻辑上会只处理最后一个<tbody>的行(虽然HLTV该页面只有一个tbody,但规范缩进是良好编程习惯)。


完整修正代码

import requests
from bs4 import BeautifulSoup

url = 'https://www.hltv.org/stats/players?startDate=2022-02-24&endDate=2023-02-24&matchType=Lan'

player_list = []

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

table = soup.find('table', class_='stats-table')

# 嵌套循环遍历所有行
for player_data in table.find_all('tbody'):
    rows = player_data.find_all('tr')
    for row in rows:
        # 提取昵称,用class定位更精准
        nick = row.find('td', class_='playerCol').text.strip()
        # 提取队伍:定位到span标签
        team_td = row.find('td', class_='teamCol')
        team = team_td.find('span').text.strip() if team_td.find('span') else '无队伍'
        # 提取其他数据
        maps = row.find('td', class_='statsDetail').text.strip()
        rounds = row.find_all('td', class_='statsDetail')[1].text.strip()
        kddiff = row.find('td', class_='kdDiffCol').text.strip()
        killdeath = row.find('td', class_='kdCol').text.strip()
        rating = row.find('td', class_='ratingCol').text.strip()
        
        # 存入字典并添加到列表
        player_info = {
            'nick': nick,
            'team': team,
            'maps': maps,
            'rounds': rounds,
            'kddiff': kddiff,
            'killdeath': killdeath,
            'rating': rating
        }
        player_list.append(player_info)

# 打印所有玩家数据示例
for idx, player in enumerate(player_list, 1):
    print(f"第{idx}名玩家:")
    print(f"  昵称: {player['nick']}")
    print(f"  队伍: {player['team']}")
    print(f"  地图数: {player['maps']}")
    print(f"  回合数: {player['rounds']}")
    print(f"  KD差: {player['kddiff']}")
    print(f"  KD比: {player['killdeath']}")
    print(f"  评分: {player['rating']}")
    print("-"*30)

额外提示

  • 优先用find()+class属性定位元素,比find_all()[index]更高效且可读性更强
  • 所有文本提取后加.strip(),可以去除多余的空格、换行符,让数据更干净
  • 增加空值判断(比如玩家无队伍的情况),避免代码运行报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 03:08:11