我在整理 wiki 表格时遇到了麻烦,希望以前做过的人能给我建议。从 List_of_current_heads_of_state_and_government 我需要国家(使用下面的代码),然后只第一次提到国家元首+他们的名字。我不确定如何隔离第一次提到的内容,因为它们都在一个单元格中。我试图提取他们的名字给了我这个错误: IndexError: list index out of range
。感谢您的帮助!
import requests
from bs4 import BeautifulSoup
wiki = "https://en.wikipedia.org/wiki/List_of_current_heads_of_state_and_government"
website_url = requests.get(wiki).text
soup = BeautifulSoup(website_url,'lxml')
my_table = soup.find('table',{'class':'wikitable plainrowheaders'})
#print(my_table)
states = []
titles = []
names = []
for row in my_table.find_all('tr')[1:]:
state_cell = row.find_all('a')[0]
states.append(state_cell.text)
print(states)
for row in my_table.find_all('td'):
title_cell = row.find_all('a')[0]
titles.append(title_cell.text)
print(titles)
for row in my_table.find_all('td'):
name_cell = row.find_all('a')[1]
names.append(name_cell.text)
print(names)
理想的输出将是 pandas df:
State | Title | Name |
原文由 aviss 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果我能理解您的问题,那么以下内容应该可以帮助您:
输出:
等等 - -