我在下面的代碼中遇到了這個錯誤:
File "\<stdin\>", line 1, in \<module\>
AttributeError: 'list' object has no attribute 'to_excel'
我想將我從維基百科抓取的表格保存到 Excel 檔案中 - 但我不知道如何調整代碼以使用 to_excel 將資料串列從終端獲取到 Excel 檔案。
當資料集的資料設定為“DataFrame”
(即df = pd.DataFrame(data, columns = \['Product', 'Price'\]).
但無法弄清楚如何調整我的代碼df = pd.read*html(str(congresstable))行 - 我認為這是問題所在。(即使用 read*_html 并從表 id 中獲取資料)
如何調整代碼以使其將 excel 檔案保存到指定的路徑?
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})
df = pd.read_html(str(congress_table))
df.to_excel (r'C:\Users\name\OneDrive\Code\.vscode\Test.xlsx', index = False, header=True)
print(df)
我期望將資料串列保存到 Excel 中指定的檔案夾路徑。
我嘗試遵循多個指南,但它們沒有顯示 read_html 專案,只有 DataFrame 解決方案。
uj5u.com熱心網友回復:
pandas.read_html()創建一個list表對應的資料框物件,因此您必須在您的情況下按索引選擇一個[0]- 您也不需要requestsand BeautifulSoup,另外,只需使用pandas.read_html()
pd.read_html(wiki_url,attrs={'id': table_id})[0]
例子
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'
congress_table = soup.find('table', )
df = pd.read_html(wiki_url,attrs={'id': table_id})[0]
df.to_excel (r'C:\Users\name\OneDrive\Code\.vscode\Test.xlsx', index = False, header=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/525791.html
