在尝试抓取Tesla维基百科页面时,我想最后抓取finces表。在对我的代码中的表类进行同样的尝试时,它几乎会抓取该页面上的每个表。有人能帮我刮一下财务表吗。以下是我的代码;
start_url='https://en.wikipedia.org/wiki/Tesla,_Inc.'
download_page=requests.get(start_url)
soup=BeautifulSoup(download_page.text)
with open ('download.html', 'w', encoding="utf-8") as file:
file.write(soup.prettify())
fullsales_table=soup.select('table.wikitable')[0]
print(fullsales_table)
您可能想要尝试pandas
。
方法如下:
import pandas as pd
import requests
page = requests.get("https://en.wikipedia.org/wiki/Tesla,_Inc.").text
df = pd.read_html(page, flavor="bs4")[7]
print(df)
df.to_csv("tesla_revenue.csv", index=False)
这将打印(并将表格保存到.csv文件中(:
Year Revenue(mil. USD) ... Total assets(mil. USD) Employees
0 2009[463] 112 ... 130 NaN
1 2010[463] 117 ... 386 899.0
2 2011[464] 204 ... 713 1417.0
3 2012[465] 413 ... 1114 2914.0
4 2013[466] 2013 ... 2417 5859.0
5 2014[467] 3198 ... 5831 10161.0
6 2015[468] 4046 ... 8068 13058.0
7 2016[469] 7000 ... 22664 17782.0
8 2017[470] 11759 ... 28655 37543.0
9 2018[471] 21461 ... 29740 48817.0
10 2019[3] 24578 ... 34309 48016.0
[11 rows x 5 columns]