【问题标题】:scraping a specific wikipedia table using python使用 python 抓取特定的维基百科表格
【发布时间】:2020-12-20 07:38:07
【问题描述】:
在尝试抓取 Tesla 维基百科页面时,我想最后抓取 finnces 表。在我的代码中尝试对表类进行相同操作时,它几乎刮掉了该页面上的每个表。有人可以帮我只刮财务表吗?以下是我的代码;
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)
【问题讨论】:
标签:
python-3.x
web-scraping
css-selectors
【解决方案1】:
你可能想试试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]