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

相关推荐
wj3055853785 小时前
课程 9:模型测试记录与 Prompt 策略
linux·人工智能·python·comfyui
程序员敲代码吗5 小时前
Go语言中Channel的实现与内存通信机制详解
excel
星寂樱易李5 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python
abigriver5 小时前
打造 Linux 离线大模型级语音输入法:Whisper.cpp + 3090 显卡加速与 Rime 中英混输终极调优指南
linux·运维·whisper
wangqiaowq5 小时前
windows下nginx的安装
linux·服务器·前端
qingfeng154155 小时前
企业微信机器人开发:如何实现自动化与智能运营?
人工智能·python·机器人·自动化·企业微信
YYRAN_ZZU6 小时前
Petalinux新建自动脚本启动
linux
charlie1145141916 小时前
嵌入式Linux驱动开发pinctrl篇(1)——从寄存器到子系统:驱动演进之路
linux·运维·驱动开发
于小猿Sup7 小时前
VMware在Ubuntu22.04驱动Livox Mid360s
linux·c++·嵌入式硬件·自动驾驶