首页 > 解决方案 > 如何使用美丽的汤从维基百科中提取表格

问题描述

我正在尝试编写一个从维基百科页面中提取表格的刮板。问题是,我可以提取页面上的所有表格,除了我实际需要的表格(该表格包含所有选举的统计数据)在美国进行)。我不认为问题出在我的标签上。
这是我的代码

from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup
from urllib.request import urlopen

#getting the wiki page
page_info=urlopen('https://en.wikipedia.org/wiki/United_States_presidential_election')

soup=BeautifulSoup(page_info, 'html.parser')

headline=soup.find('table', "wikitable sortable jquery-tablesorter")
print(headline)

我认为我缺少一些至关重要的东西,但我无法理解它。有人能帮助我吗。

标签: python-3.xweb-scrapingbeautifulsoupurllib

解决方案


一种方法是:

import pandas as pd
import requests
from bs4 import BeautifulSoup


page = requests.get('https://en.wikipedia.org/wiki/United_States_presidential_election').text
soup = BeautifulSoup(page, 'html.parser')
table = soup.find('table', class_="wikitable sortable")

df = pd.read_html(str(table))
df = pd.concat(df)
print(df)
df.to_csv("elections.csv", index=False)

哪个输出:

     Year                                    Party  ... Electoral votes      Notes
0    1788                              Independent  ...        69 / 138        NaN
1    1788                               Federalist  ...        34 / 138        NaN
2    1788                               Federalist  ...         9 / 138        NaN
3    1788                               Federalist  ...         6 / 138        NaN
4    1788                               Federalist  ...         6 / 138        NaN
..    ...                                      ...  ...             ...        ...
[219 rows x 8 columns]

或者一个.csv看起来像这样的文件:

在此处输入图像描述

注意:每当您进行抓取时,请始终关闭JS(JavaScript)。BeautifulSoup看不到动态呈现的内容。这样你就不会得到任何回报,因为没有JS你所追求的标签的类别是不同的。


推荐阅读