如何用Python将HTML表转换为CSV

559 阅读1分钟

给定一个文件中的HTML表(代码),或在一个给定的URL。首先,通过调用Pandas的pd.read_html() ,传递HTML文档的URL,将所有HTML表加载到Python脚本中。结果是一个DataFrame的列表,文件中每个HTML表都有一个。其次,将任何特定的DataFrame转换为CSV,通过调用 [df.to_csv()](https://blog.finxter.com/how-to-export-pandas-dataframe-to-csv-example/)函数。

这是一般的例子,替换你的具体URL和输出CSV文件。

import pandas as pd

html = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
csv = 'my_file.csv'

# 1. Read all HTML tables from a given URL
tables = pd.read_html(html)

# 2. Write first table, for example, to the CSV file
tables[0].to_csv(csv)

例子--将Python的Wiki页面表导出到CSV中

给出Python维基页面的第一个描述性表格。

你通过使用上面概述的以下方法将其转换为CSV。

import pandas as pd


# 1. Read all HTML tables from a given URL
tables = pd.read_html('https://en.wikipedia.org/wiki/Python_(programming_language)')

# 2. Write first table, for example, to the CSV file
tables[0].to_csv('my_file.csv')

所以,基本上我们把下面的输入表(HTML)转换。

到下面的输出。

如何用Python将文件中的HTML表转换为CSV文件

💬 挑战。给出一个存储在文件中的单一HTML表 。如何在Python中把该表文件转换为CSV文件?'my_file.html'

如果你用文件路径或URL作为参数,pandas.read_html() 函数就能工作!要在Python中把一个HTML表文件'my_file.html' 转为CSV文件'my_file.csv' ,请使用以下三个步骤。

  1. 导入pandas库
  2. 将HTML表作为一个DataFrame来读取df 通过调用pd.read_html('my_file.html')
  3. 如果你不需要行号索引,通过调用df.to_csv('my_file.csv', index=False) ,将DataFrame写成CSV。

下面是工作的具体代码。

import pandas as pd


 # Select the only (first) table using indexing [0]
df = pd.read_html('my_file.html')[0]

# Write DataFrame to CSV - no index required
df.to_csv('my_file.csv', index=False)

这是原始的HTML表格文件'my_file.html'

这是转换后的CSV文件'my_file.csv'