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

Python/BeautifulSoup移除元素标签:Excel导出残留及get_text报错问题

解决fbref爬取数据导出Excel带HTML标签的问题

问题根源

你遇到的问题核心是:DataFrame里的部分单元格实际仍是BeautifulSoup的Tag对象,打印时会自动转成文本显示,但导出Excel时会保留原始HTML结构;调用get_text()报错,是因为你可能对非Tag对象(比如已转成字符串的元素)或整个Series/列直接调用了该方法,而这类对象本身没有get_text属性。

解决步骤

1. 从源头提取纯文本(推荐)

在解析HTML、填充DataFrame的阶段就把Tag对象转换成纯文本,避免后续处理麻烦。示例代码:

import requests
from bs4 import BeautifulSoup
import pandas as pd

# 请求目标页面
url = "你的fbref英超球员数据页面URL"
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
soup = BeautifulSoup(response.text, 'html.parser')

# 定位目标数据表格
target_table = soup.find('table', id='stats_standard')
thead = target_table.find('thead')
tbody = target_table.find('tbody')

# 提取表头
headers = [th.get_text(strip=True) for th in thead.find_all('th')]

# 提取数据行并转成纯文本
player_data = []
for row in tbody.find_all('tr'):
    cols = row.find_all('td')
    # 对每个td标签提取文本,空值填充为空字符串
    row_content = [col.get_text(strip=True) if col else '' for col in cols]
    if row_content:
        player_data.append(row_content)

# 构建DataFrame并导出
df = pd.DataFrame(player_data, columns=headers)
print(df.head())
df.to_excel('premier_league_players.xlsx', index=False)

2. 批量清洗已有带HTML标签的DataFrame

如果已经生成了带HTML标签的DataFrame,可通过applymap批量处理:

def strip_html_tags(content):
    # 仅对包含HTML标签的字符串进行清洗
    if isinstance(content, str) and ('<' in content or '>' in content):
        return BeautifulSoup(content, 'html.parser').get_text(strip=True)
    return content

# 清洗整个DataFrame的所有单元格
cleaned_df = df.applymap(strip_html_tags)
cleaned_df.to_excel('cleaned_player_data.xlsx', index=False)

3. 避免get_text()报错的注意事项

  • 不要对DataFrame的列/Series直接调用get_text(),需对每个元素单独处理(比如用apply或列表推导)。
  • 调用get_text()前,先判断元素是否为BeautifulSoup的Tag对象,或是包含HTML标签的字符串,避免对纯文本调用该方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 06:12:13