Python 实战:将 HTML 表格一键导出为 Excel(xlsx)

在数据采集、网页解析或自动化报表场景中,我们经常会遇到这样一个需求:

从 HTML 页面中提取表格数据,并导出为 Excel 文件

本文将使用 BeautifulSoup + Pandas + OpenPyXL ,实现一个通用、简单、可复用 的工具函数,把 HTML 中的 <table> 表格直接导出为 .xlsx 文件。


一、实现思路

整体流程非常清晰:

  1. 使用 BeautifulSoup 解析 HTML
  2. 查找页面中所有 <table> 标签
  3. 使用 pandas.read_html 将表格转为 DataFrame
  4. 使用 ExcelWriter 将多个表格写入 Excel 的不同 Sheet

二、环境准备

1️⃣ 安装依赖

bash 复制代码
pip install beautifulsoup4 pandas openpyxl lxml

lxmlpandas.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 上海

相关推荐
0思必得01 小时前
[Web自动化] Selenium浏览器对象属性
前端·python·selenium·自动化·web自动化
济6172 小时前
linux 系统移植(第九期)----Linux 内核顶层 Makefile- make xxx_defconfig 过程-- Ubuntu20.04
linux·运维·服务器
七夜zippoe2 小时前
NumPy向量化计算实战:从入门到精通的性能优化指南
python·性能优化·架构·numpy·广播机制·ufunc
宴之敖者、2 小时前
Linux——yum和vim
linux·运维·服务器
小二·2 小时前
Python Web 开发进阶实战:边缘智能网关 —— 在 Flask + Vue 中构建轻量级 IoT 边缘计算平台
前端·python·flask
人道领域2 小时前
JavaWeb从入门到进阶(Maven依赖管理)
linux·python·maven
Hacker_seagull2 小时前
Python环境配置~超简单
python
FJW0208142 小时前
Python深浅拷贝
开发语言·python
一位不知名民工2 小时前
python3从入门到精通(五): pyhhon协程之asyncio模块(异步IO)(一)
运维·python