You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pd.read_html获取指定ID表格后导出Excel报错的解决方法

解决read_html返回列表无法调用to_excel的问题

你遇到的错误是:

File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'to_excel'

问题根源很明确:pd.read_html()方法始终返回一个DataFrame对象的列表,哪怕你传入的HTML里只有一个表格。你直接把这个列表赋值给df,自然没法调用只有DataFrame才有的to_excel()方法。

修改方法

只需要从返回的列表中取出第一个(也是唯一一个)DataFrame对象即可,把这行代码:

df = pd.read_html(str(congress_table))

改成:

df = pd.read_html(str(congress_table))[0]

修改后的完整代码

from bs4 import BeautifulSoup
import requests
import pandas as pd

wiki_url = 'https://en.wikipedia.org/wiki/List_of_current_members_of_the_United_States_House_of_Representatives'
table_id = 'votingmembers'

response = requests.get(wiki_url)
soup = BeautifulSoup(response.text, 'html.parser')

congress_table = soup.find('table', attrs={'id': table_id})
# 取列表第一个元素得到DataFrame
df = pd.read_html(str(congress_table))[0]

df.to_excel(r'C:\Users\name\OneDrive\Code\.vscode\Test.xlsx', index=False, header=True)

print(df)

这样修改后,df就变成了标准的DataFrame对象,就能正常调用to_excel()方法把数据保存到指定路径的Excel文件里了。

内容的提问来源于stack exchange,提问作者gcl_codeguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:15:50