如何用BeautifulSoup提取表格caption或summary值作为Excel工作表名
实现方案
你原代码的问题有两处:
- 遍历表格提取caption后,额外执行了
titles = []把已经收集到的标题清空了 - 用
find_all获取caption标签返回的是列表对象,没有提取标签内的文本内容,也没有加summary属性的兜底逻辑
同时需要额外处理Excel工作表名称的限制:不能超过31个字符,不能包含\ / ? * [ ]这些特殊字符
下面是修改后可直接运行的完整代码:
import pandas as pd import requests from bs4 import BeautifulSoup from pandas import ExcelWriter import re url = 'https://zoek.officielebekendmakingen.nl/kst-35570-2.html' page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') # 同时获取表格df和对应的原始table标签对象 tables_df = pd.read_html(url, attrs = {'class': 'kio2 portrait'}) tables = soup.find_all('table', class_="kio2 portrait") sheet_names = [] for table in tables: # 优先取caption文本 caption_tag = table.find("caption", class_="table-title") if caption_tag and caption_tag.text.strip(): title = caption_tag.text.strip() else: # 兜底取summary属性 title = table.get("summary", "").strip() # 还是没拿到标题就用默认命名 if not title: title = f"表格_{len(sheet_names)+1}" # 处理Excel不允许的特殊字符 title = re.sub(r'[\\/:*?"<>|]', '_', title) # 处理长度限制,最多31个字符 title = title[:31] sheet_names.append(title) writer = pd.ExcelWriter('output.xlsx') for df, sheet_name in zip(tables_df, sheet_names): df.to_excel(writer, index=True, sheet_name=sheet_name) writer.save()
关键逻辑说明
- 标题提取优先级:
caption标签文本 >table标签的summary属性 > 自动生成的默认命名 - 自动过滤Excel工作表名称的非法字符,自动截断超长名称,避免导出报错
内容的提问来源于stack exchange,提问作者Tobias
相关产品推荐
相关产品推荐

