以下是一个使用Python保存HTML表格中数据的示例代码:
import requests
import pandas as pd
# 发送HTTP请求获取HTML页面
url = "http://example.com/table.html"
response = requests.get(url)
html = response.text
# 使用pandas的read_html函数解析HTML表格
tables = pd.read_html(html)
# 假设想要保存第一个表格的数据
table_data = tables[0]
# 将数据保存为CSV文件
table_data.to_csv("table_data.csv", index=False)
# 将数据保存为Excel文件
table_data.to_excel("table_data.xlsx", index=False)
以上代码使用了requests
库发送HTTP请求获取HTML页面,并使用pandas
库的read_html
函数解析HTML表格。然后,可以选择需要保存的表格数据并将其保存为CSV文件或Excel文件。
请注意,要运行此代码,您需要先安装requests
和pandas
库。您可以使用以下命令来安装它们:
pip install requests pandas
另外,请将代码中的URL替换为您要保存数据的HTML表格的实际URL。
上一篇:保存HTML表格对象