以下是使用BeautifulSoup库合并表格并导出为.csv文件的示例代码:
from bs4 import BeautifulSoup
import csv
# 读取HTML文件
with open('input.html') as file:
soup = BeautifulSoup(file, 'html.parser')
# 查找所有表格
tables = soup.find_all('table')
# 创建CSV文件
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
# 遍历每个表格
for table in tables:
# 查找所有行
rows = table.find_all('tr')
# 遍历每一行
for row in rows:
# 查找所有单元格
cells = row.find_all(['th', 'td'])
# 提取每个单元格的文本内容
data = [cell.get_text(strip=True) for cell in cells]
# 写入CSV文件
writer.writerow(data)
在上述代码中,我们首先使用BeautifulSoup库读取HTML文件,并找到所有的表格。然后,我们创建一个CSV文件,并使用csv.writer对象将表格数据写入CSV文件。
在遍历每个表格时,我们首先找到所有的行,然后遍历每一行。对于每一行,我们找到所有的单元格,并提取其文本内容。最后,我们使用writer.writerow()方法将每一行的数据写入CSV文件。
请确保将输入HTML文件的名称替换为实际文件的名称,并将输出CSV文件的名称替换为您想要的名称。