Python 抓取 table 的所有列,但我只想查看其中一列

Python scrapes all columns of a table, but I only want to see one of the columns

我正在使用 Python 来抓取 U.S 的名字。来自 Ballotpedia 的大会 (https://ballotpedia.org/List_of_current_members_of_the_U.S._Congress)。我当前的代码为我提供了两个表(参议院和众议院)中每一个的所有四列。这是我当前的代码:

import requests
from bs4 import BeautifulSoup
import pandas as pd

list = ['https://ballotpedia.org/List_of_current_members_of_the_U.S._Congress']

all_tables = pd.read_html(list[0])
senators = all_tables[3]
house_members = all_tables[6]
congress = senators.append(house_members)

congress.to_csv('3-New Congressmen.csv')

显然,我一直在尝试使用第 7-10 行,但不喜欢只获取立法者姓名的方法。我只对名称栏感兴趣。

是不是我忽略了投票百科页面的检查功能?或者是否需要额外的一行代码来指定我想要的列?非常感谢您的帮助!

要仅获取立法者的姓名,您可以执行以下操作:

import pandas as pd

url = "https://ballotpedia.org/List_of_current_members_of_the_U.S._Congress"

dfs = pd.read_html(url)

legislators_df = dfs[3]["Name"]
house_members = dfs[6]["Name"]


pd.concat([legislators_df, house_members]).to_csv("out.csv", index=False)

创建 out.csv:

0             Richard Shelby
1           Tommy Tuberville
2             Lisa Murkowski
3         Daniel S. Sullivan
4                 Mark Kelly
5             Kyrsten Sinema
6               John Boozman
7                 Tom Cotton
8           Dianne Feinstein
9               Alex Padilla
10            Michael Bennet
...