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

相关推荐
Java后端的Ai之路19 小时前
【Python 教程15】-Python和Web
python
Coder个人博客20 小时前
Linux6.19-ARM64 mm mmu子模块深入分析
大数据·linux·车载系统·系统架构·系统安全·鸿蒙系统
冬奇Lab21 小时前
一天一个开源项目(第15篇):MapToPoster - 用代码将城市地图转换为精美的海报设计
python·开源
Doro再努力1 天前
Vim 快速上手实操手册:从入门到生产环境实战
linux·编辑器·vim
wypywyp1 天前
8. ubuntu 虚拟机 linux 服务器 TCP/IP 概念辨析
linux·服务器·ubuntu
二十雨辰1 天前
[python]-AI大模型
开发语言·人工智能·python
Doro再努力1 天前
【Linux操作系统10】Makefile深度解析:从依赖推导到有效编译
android·linux·运维·服务器·编辑器·vim
senijusene1 天前
Linux软件编程:IO编程,标准IO(1)
linux·运维·服务器
Yvonne爱编码1 天前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
忧郁的橙子.1 天前
02-本地部署Ollama、Python
linux·运维·服务器