在数据采集、网页解析或自动化报表场景中,我们经常会遇到这样一个需求:
从 HTML 页面中提取表格数据,并导出为 Excel 文件
本文将使用 BeautifulSoup + Pandas + OpenPyXL ,实现一个通用、简单、可复用 的工具函数,把 HTML 中的 <table> 表格直接导出为 .xlsx 文件。
一、实现思路
整体流程非常清晰:
- 使用 BeautifulSoup 解析 HTML
- 查找页面中所有
<table>标签 - 使用 pandas.read_html 将表格转为 DataFrame
- 使用 ExcelWriter 将多个表格写入 Excel 的不同 Sheet
二、环境准备
1️⃣ 安装依赖
bash
pip install beautifulsoup4 pandas openpyxl lxml
lxml是pandas.read_html推荐的解析器,性能更好。
三、核心代码实现
1️⃣ HTML 表格导出函数
python
from bs4 import BeautifulSoup
import pandas as pd
def html_table_to_xlsx(html_content, output_file):
"""
将 HTML 中的表格提取并导出为 xlsx 文件。
:param html_content: HTML 文本内容
:param output_file: 导出的 xlsx 文件路径
"""
# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(html_content, 'html.parser')
# 查找 HTML 中的所有表格
tables = soup.find_all('table')
if not tables:
print("HTML 中没有找到表格!")
return
# 逐个解析表格并导出到 Excel
with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
for i, table in enumerate(tables):
# 将 HTML table 转为 DataFrame
df = pd.read_html(str(table))[0]
# 不同表格写入不同的 sheet
sheet_name = f"Sheet{i + 1}"
df.to_excel(writer, index=False, sheet_name=sheet_name)
print(f"表格已成功导出到 {output_file}")
四、示例演示
1️⃣ 示例 HTML 内容
python
html_content = """
<html>
<head><title>测试表格</title></head>
<body>
<table border="1">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>城市</th>
</tr>
<tr>
<td>张三</td>
<td>28</td>
<td>北京</td>
</tr>
<tr>
<td>李四</td>
<td>34</td>
<td>上海</td>
</tr>
</table>
</body>
</html>
"""
2️⃣ 调用函数导出 Excel
python
html_table_to_xlsx(html_content, "output.xlsx")
执行后,会在当前目录生成一个 output.xlsx 文件,内容如下:
| 姓名 | 年龄 | 城市 |
|---|---|---|
| 张三 | 28 | 北京 |
| 李四 | 34 | 上海 |