python-3.x - 如何使用美丽的汤从维基百科中提取表格
问题描述
我正在尝试编写一个从该维基百科页面中提取表格的刮板。问题是,我可以提取页面上的所有表格,除了我实际需要的表格(该表格包含所有选举的统计数据)在美国进行)。我不认为问题出在我的标签上。
这是我的代码
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)
我认为我缺少一些至关重要的东西,但我无法理解它。有人能帮助我吗。
解决方案
一种方法是:
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
你所追求的标签的类别是不同的。
推荐阅读
- google-apps-script - 扫描 COLUMN 以获取键集的首字母缩写,获取该 ROW 的值,然后获取不同 CELLS 的 CONTENTS
- typescript - cordova-plugin-qrscanner: 错误: 没有为 DefaultDecoderFactory(ArrayList) 找到合适的构造函数
, , ) - mikrotik - Mikrotik Wap AC. Unresettable?
- php - 如何在不使用 PHP explode() 的情况下在逗号之后获取
- python - 从 Python 非标准库导入模块
- vb.net - Roslyn context.SemanticModel.GetDeclaredSymbol() 从 InvocationExpression 返回 NULL
- python - Python内部函数中传递变量的区别
- c# - 当 GameObject 移动时,Transform.position 返回 0 0 0
- python - 如何录制内部音频?Python
- python - Python 无法处理带有父目录部分的 Windows 长路径