Python实现将HTML表格一键导出为Excel

Written by

in

文章目录
  • pip install beautifulsoup4 pandas openpyxl
  • 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): # 将表格转为 DataFrame df = pd.read_html(str(table))[0] # 写入 Excel,不同表格写入不同的 sheet sheet_name = f”Sheet{i + 1}” df.to_excel(writer, index=False, sheet_name=sheet_name) print(f”表格已成功导出到 {output_file}”) # 示例 HTML 内容 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> “”” # 调用函数,将 HTML 中的表格导出为 Excel 文件 html_table_to_xlsx(html_content, “output.xlsx”)
  • Python 解析 HTML 表格并转换为 Excel 表格 在处理数据时,我们常常会遇到需要从 HTML 表格中提取信息并将其转换为 Excel 文件的需求。本文将介绍如何使用 Python 来解析 HTML 表格,并将其转换为 Excel 表格。 准备工作 在开始之前,请确保您的环境中已经安装了必要的库: beautifulsoup4:用于解析 HTML。 pandas:用于处理和转换数据。 openpyxl:用于生成 Excel 文件。 可以通过以下命令安装这些库: pip install beautifulsoup4 pandas openpyxl 解析 HTML 表格 首先,我们需要从一个 HTML 文件中提取表格数据。假设我们有一个简单的 HTML 文件,其中包含一个表格。 HTML 示例代码: <!DOCTYPE html> <html> <body> <table border=”1″> <tr> <th>姓名</th> <th>年龄</th> <th>职业</th> </tr> <tr> <td>张三</td> <td>25</td> <td>工程师</td> </tr> <tr> <td>李四</td> <td>30</td> <td>医生</td> </tr> </table> </body> </html> 接下来,我们将使用 BeautifulSoup 来解析这个 HTML 文件并提取表格数据。 解析代码示例 from bs4 import BeautifulSoup # 读取 HTML 文件 with open(‘example.html’, ‘r’, encoding=’utf-8′) as f: html_content = f.read() # 使用 BeautifulSoup 解析 HTML soup = BeautifulSoup(html_content, ‘html.parser’) # 查找所有的表格 tables = soup.find_all(‘table’) # 遍历每个表格 for table in tables: # 提取表头 headers = [header.text for header in table.find_all(‘th’)] # 提取表格数据 data = [] for row in table.find_all(‘tr’)[1:]: # 跳过表头行 cells = row.find_all(‘td’) row_data = [cell.text for cell in cells] data.append(row_data) print(“表头:”, headers) print(“数据:”, data) 将数据转换为 Excel 现在我们已经成功提取了表格数据,接下来我们将使用 Pandas 将其转换为 Excel 文件。 转换代码示例 import pandas as pd # 创建 DataFrame df = pd.DataFrame(data, columns=headers) # 将 DataFrame 写入 Excel 文件 df.to_excel(‘output.xlsx’, index=False) 上述代码将提取的表格数据保存到名为 output.xlsx 的 Excel 文件中。 完整代码示例 以下是完整的代码示例,结合了 HTML 解析和 Excel 转换的功能。 from bs4 import BeautifulSoup import pandas as pd # 读取 HTML 文件 with open(‘example.html’, ‘r’, encoding=’utf-8′) as f: html_content = f.read() # 使用 BeautifulSoup 解析 HTML soup = BeautifulSoup(html_content, ‘html.parser’) # 查找所有的表格 tables = soup.find_all(‘table’) # 遍历每个表格 for i, table in enumerate(tables): # 提取表头 headers = [header.text for header in table.find_all(‘th’)] # 提取表格数据 data = [] for row in table.find_all(‘tr’)[1:]: # 跳过表头行 cells = row.find_all(‘td’) row_data = [cell.text for cell in cells] data.append(row_data) # 创建 DataFrame df = pd.DataFrame(data, columns=headers) # 将 DataFrame 写入 Excel 文件 df.to_excel(f’table_{i+1}.xlsx’, index=False) 到此这篇关于Python实现将HTML表格一键导出为Excel的文章就介绍到这了,更多相关Python HTML表格转Excel内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: 利用Python实现Excel表格转换为HTML格式 Python实现Excel表格转HTML Python实现读取HTML表格 pd.read_html() 用Python生成HTML表格的方法示例 python实现将html表格转换成CSV文件的方法 Python实现简单HTML表格解析的方法
  • 目录
    • 一、依赖安装
    • 二、实现代码
    • 三、最终效果
    • 四、方法补充

    在数据处理和网页爬虫项目中,我们经常会遇到从 HTML 页面中提取表格的需求。手动复制粘贴不仅低效,还容易出错。本文将带你使用 Python + BeautifulSoup + pandas,实现 一键将 HTML 中的多个表格导出为 Excel 文件(.xlsx),支持多 Sheet 自动分表,代码简洁、实用性强。

    pip install beautifulsoup4 pandas openpyxl

    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):
                # 将表格转为 DataFrame
                df = pd.read_html(str(table))[0]
                # 写入 Excel,不同表格写入不同的 sheet
                sheet_name = f"Sheet{i + 1}"
                df.to_excel(writer, index=False, sheet_name=sheet_name)
    
    
        print(f"表格已成功导出到 {output_file}")
    
    
    # 示例 HTML 内容
    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>
    """
    
    
    # 调用函数,将 HTML 中的表格导出为 Excel 文件
    html_table_to_xlsx(html_content, "output.xlsx")
    

    Python 解析 HTML 表格并转换为 Excel 表格

    在处理数据时,我们常常会遇到需要从 HTML 表格中提取信息并将其转换为 Excel 文件的需求。本文将介绍如何使用 Python 来解析 HTML 表格,并将其转换为 Excel 表格。

    准备工作

    在开始之前,请确保您的环境中已经安装了必要的库:

    • beautifulsoup4:用于解析 HTML。
    • pandas:用于处理和转换数据。
    • openpyxl:用于生成 Excel 文件。

    可以通过以下命令安装这些库:

    pip install beautifulsoup4 pandas openpyxl
    

    解析 HTML 表格

    首先,我们需要从一个 HTML 文件中提取表格数据。假设我们有一个简单的 HTML 文件,其中包含一个表格。

    HTML 示例代码:

    <!DOCTYPE html>
    <html>
    <body>
    
    <table border="1">
      <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>职业</th>
      </tr>
      <tr>
        <td>张三</td>
        <td>25</td>
        <td>工程师</td>
      </tr>
      <tr>
        <td>李四</td>
        <td>30</td>
        <td>医生</td>
      </tr>
    </table>
    
    </body>
    </html>
    

    接下来,我们将使用 BeautifulSoup 来解析这个 HTML 文件并提取表格数据。

    解析代码示例

    from bs4 import BeautifulSoup
    
    # 读取 HTML 文件
    with open('example.html', 'r', encoding='utf-8') as f:
        html_content = f.read()
    
    # 使用 BeautifulSoup 解析 HTML
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 查找所有的表格
    tables = soup.find_all('table')
    
    # 遍历每个表格
    for table in tables:
        # 提取表头
        headers = [header.text for header in table.find_all('th')]
        
        # 提取表格数据
        data = []
        for row in table.find_all('tr')[1:]:  # 跳过表头行
            cells = row.find_all('td')
            row_data = [cell.text for cell in cells]
            data.append(row_data)
        
        print("表头:", headers)
        print("数据:", data)
    

    将数据转换为 Excel

    现在我们已经成功提取了表格数据,接下来我们将使用 Pandas 将其转换为 Excel 文件。

    转换代码示例

    import pandas as pd
    
    # 创建 DataFrame
    df = pd.DataFrame(data, columns=headers)
    
    # 将 DataFrame 写入 Excel 文件
    df.to_excel('output.xlsx', index=False)
    

    上述代码将提取的表格数据保存到名为 output.xlsx 的 Excel 文件中。

    完整代码示例

    以下是完整的代码示例,结合了 HTML 解析和 Excel 转换的功能。

    from bs4 import BeautifulSoup
    import pandas as pd
    
    # 读取 HTML 文件
    with open('example.html', 'r', encoding='utf-8') as f:
        html_content = f.read()
    
    # 使用 BeautifulSoup 解析 HTML
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 查找所有的表格
    tables = soup.find_all('table')
    
    # 遍历每个表格
    for i, table in enumerate(tables):
        # 提取表头
        headers = [header.text for header in table.find_all('th')]
        
        # 提取表格数据
        data = []
        for row in table.find_all('tr')[1:]:  # 跳过表头行
            cells = row.find_all('td')
            row_data = [cell.text for cell in cells]
            data.append(row_data)
        
        # 创建 DataFrame
        df = pd.DataFrame(data, columns=headers)
        
        # 将 DataFrame 写入 Excel 文件
        df.to_excel(f'table_{i+1}.xlsx', index=False)
    

    到此这篇关于Python实现将HTML表格一键导出为Excel的文章就介绍到这了,更多相关Python HTML表格转Excel内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

    您可能感兴趣的文章:

    • 利用Python实现Excel表格转换为HTML格式
    • Python实现Excel表格转HTML
    • Python实现读取HTML表格 pd.read_html()
    • 用Python生成HTML表格的方法示例
    • python实现将html表格转换成CSV文件的方法
    • Python实现简单HTML表格解析的方法

    站内搜索