首页 > 解决方案 > 抓取维基百科表格 - 美国参议员名单

问题描述

我想创建一个表格,我可以从以下维基百科网页中获取第 116 届国会的所有美国参议员名单。

截至目前,我正在使用以下代码。

from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import pandas as pd
#import censusdata

url = "https://en.wikipedia.org/wiki/List_of_current_United_States_senators"
page = requests.get(url).content
soup = BeautifulSoup(page, features = 'html.parser')
table=soup.find("table", class_="wikitable sortable jquery-tablesorter")
# print(table)
state=[]
senator=[]
party=[]
born=[]
assumed_office=[]
term=[]

for row in table.find_all('tr')[1:]:
    col=row.find_all('td')
    col1=col[0].string.strip()
    state.append(col1)
    col2=col[2].string.strip()
    senator.append(col2)
    col3=col[3].string.strip()
    party.append(col2)
    col4=col[4].string.strip()
    born.append(col4)
    col5=col[7].string.strip()
    assumed_office.append(col5)
    col6=col[8].string.strip()
    term.append(col6)

columns={'State':state,'Senator':senator,'Party Affiliated':party,'Birth Date':born,'Assumed Office':assumed_office,'Next Election':term}

df = pd.DataFrame(columns)
print(df)

但是,我最终得到了这个错误。

Traceback (most recent call last):
  File "c:\file_path\US Senate.py", line 23, in <module>
    for row in table.find_all('tr')[1:]:
AttributeError: 'NoneType' object has no attribute 'find_all'

我想要做的就是从每一列中获取以下数据:姓名、参议员所代表的州、党派成员、年龄、他们何时上任以及下次选举的时间。对此的任何帮助都非常感谢。

标签: pythonpython-3.xbeautifulsoup

解决方案


只需使用pd.read_html

import requests
import pandas as pd
#import censusdata

url = "https://en.wikipedia.org/wiki/List_of_current_United_States_senators"
page = requests.get(url).content

dfs = pd.read_html(page)

df = dfs[4]

df['Residence'] = [elem.split('[')[0] for elem in list(df['Residence'])]
df = df.drop('Image', axis = 1)
df['Party'] = df['Party.1']
df = df.drop('Party.1', axis = 1)

df.to_csv('D:\\senators.csv', index = False)

文件截图csv(我做了一些格式化,使它看起来整洁):

在此处输入图像描述


推荐阅读