使用Pandas read_html导出多表至CSV遇AttributeError问题求助
Hey there! Let's break down why you're hitting that AttributeError: 'list' object has no attribute 'to_csv' error and how to fix it.
Why the Error Happens
The pandas.read_html() function doesn't return a single DataFrame—it returns a list of DataFrames, one for each table found in your example.html file. When you try calling .to_csv() directly on that list, Python throws an error because lists don't have that method.
Two Common Solutions for Exporting Multiple Tables to One CSV
Depending on how you want your final CSV structured, use one of these approaches:
1. Combine Tables with the Same Structure (Vertical Stack)
If all your HTML tables have identical columns and you want to stack them into one big table:
import pandas as pd # Read all tables from the HTML file table_list = pd.read_html('example.html') # Combine all DataFrames into one (ignore_index resets row numbers) combined_table = pd.concat(table_list, ignore_index=True) # Export to CSV combined_table.to_csv('combined_output.csv', index=False)
ignore_index=Trueensures your final table has continuous row numbers instead of keeping the original indices from each individual table.index=Falseprevents pandas from adding an extra index column to your CSV.
2. Write Tables Separately (With Headers/Blank Lines)
If your tables have different structures and you want to keep them distinct in the CSV (e.g., each table with its own header, separated by blank lines):
import pandas as pd # Read all tables table_list = pd.read_html('example.html') # Open the CSV file in write mode with open('separate_tables_output.csv', 'w', newline='', encoding='utf-8') as csv_file: for idx, table in enumerate(table_list): # Only write the header for the first table (adjust if you want headers for all) table.to_csv(csv_file, index=False, header=idx == 0) # Add a blank line between tables for readability csv_file.write('\n')
header=idx == 0tells pandas to write the column headers only once (for the first table). Change this toheader=Trueif you want each table to show its own headers.newline=''avoids extra blank lines in the CSV on Windows systems.
Quick Debug Tip
Before exporting, you can check how many tables were read and inspect their structure:
print(f"Number of tables found: {len(table_list)}") # Inspect the first table's columns print(table_list[0].columns)
内容的提问来源于stack exchange,提问作者statsguy

