微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python 为我提供了一张表格的两列,但我只希望它给我其中一列

如何解决Python 为我提供了一张表格的两列,但我只希望它给我其中一列

我正在使用 Python 从 Ballotpedia (https://ballotpedia.org/Alaska_Supreme_Court) 中抓取阿拉斯加最高法院法官的姓名。我当前的代码在“任命者”列中同时提供了法官的姓名以及人员的姓名。这是我当前的代码

import requests
from bs4 import BeautifulSoup
import pandas as pd

list = ['https://ballotpedia.org/Alaska_Supreme_Court']

temp_dict = {}

for page in list:
    r = requests.get(page)
    soup = BeautifulSoup(r.content,'html.parser')

    temp_dict[page.split('/')[-1]] = [item.text for item in soup.select("table.wikitable.sortable.jquery-tablesorter a")]

df = pd.DataFrame.from_dict(temp_dict,orient='index').transpose()
df.to_csv('18-TEST.csv')

我一直在尝试使用这条线:

temp_dict[page.split('/')[-1]] = [item.text for item in soup.select("table.wikitable.sortable.jquery-tablesorter a")]

我在网页上使用检查功能有点缺乏经验,所以当我尝试将“tr”或“td”(我在“tbody”下找到)放在“tablesorter”之后时,我可能会尝试错误的东西.在这一点上我有点迷茫,并且在寻找这方面的资源时遇到了麻烦。你能帮我让python给我法官列而不是任命列吗?谢谢!

解决方法

有不同的方法可以得到结果。

选项#1

对列表进行切片并每隔一个元素选取一个:

soup.select("table.wikitable.sortable.jquery-tablesorter a")][0::2]

示例:

import requests
from bs4 import BeautifulSoup
import pandas as pd

lst = ['https://ballotpedia.org/Alaska_Supreme_Court']

temp_dict = {}

for page in lst:
    r = requests.get(page)
    soup = BeautifulSoup(r.content,'html.parser')

    temp_dict[page.split('/')[-1]] = [item.text for item in soup.select("table.wikitable.sortable.jquery-tablesorter a")][0::2]

pd.DataFrame.from_dict(temp_dict,orient='index').transpose().to_csv('18-TEST.csv',index=False)

选项#2

使您的选择更加具体,并仅选择 td 中的第一个 tr

soup.select("table.wikitable.sortable.jquery-tablesorter  tr > td:nth-of-type(1)")]

示例

import requests
from bs4 import BeautifulSoup
import pandas as pd

list = ['https://ballotpedia.org/Alaska_Supreme_Court']

temp_dict = {}

for page in list:
    r = requests.get(page)
    soup = BeautifulSoup(r.content,'html.parser')

    temp_dict[page.split('/')[-1]] = [item.text for item in soup.select("table.wikitable.sortable.jquery-tablesorter  tr > td:nth-of-type(1)")]

pd.DataFrame.from_dict(temp_dict,index=False)

选项#3

使用 pandas 功能 read_html()

示例

import pandas as pd
df = pd.read_html('https://ballotpedia.org/Alaska_Supreme_Court')[2]
df.Judge.to_csv('18-TEST.csv',index=False)
,

首先,请注意这是从 here 中提取的代码。

现在,如果您不知道有多少行或列,这将为您提供一个包含所有列的数据框,对应于网页上的表格。如果您不需要,请随意删除其中一列。

import requests
from bs4 import BeautifulSoup
import pandas as pd

# I'll do it for the one page example
page = 'https://ballotpedia.org/Alaska_Supreme_Court'

temp_dict = {}
r = requests.get(page)
soup = BeautifulSoup(r.content,'html.parser')

# this finds the first table with the class specified
table = soup.find('table',attrs={'class':'wikitable sortable jquery-tablesorter'})
# get all rows of the above table
rows = table.find_all('tr') 
data = []
for row in rows:
    cols = row.find_all('td')
    cols = [ele.text.strip() for ele in cols]
    data.append([ele for ele in cols if ele])
# turn it into a pandas dataframe
df = pd.DataFrame(data)
,

我想分享另一种方法,让您以所需格式制作表格:

import pandas as pd
# extracting table and making it dataframe
frame = pd.read_html('https://ballotpedia.org/Alaska_Supreme_Court',attrs={"class":"wikitable sortable jquery-tablesorter"})[0]

# drop unwanted columns
frame.drop("Appointed By",axis=1,inplace=True)

# save dataframe as csv
frame.to_csv("desired/path/output.csv",index=False)

打印 frame 将输出为: |法官| |-----| |丹尼尔温弗里 |乔尔·哈罗德·博尔格| |彼得·乔恩·马森| |苏珊·卡尼| |达里奥·博尔赫桑|

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。