python-3.x - 有选择地使用 Python 抓取维基百科表格

标签 python-3.x web-scraping beautifulsoup wikipedia

我在整理 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 |

最佳答案

通过导入 wikipedia,我找到了一个 super 简单的方法来做到这一点。 python 模块,然后使用 pandas 的 read_html将其放入数据框中。

从那里你可以应用你想要的任何数量的分析。

import pandas as pd
import wikipedia as wp
html = wp.page("List_of_video_games_considered_the_best").html().encode("UTF-8")
try: 
    df = pd.read_html(html)[1]  # Try 2nd table first as most pages contain contents table first
except IndexError:
    df = pd.read_html(html)[0]
print(df.to_string())

或者,如果您想从命令行调用它:

只需调用python yourfile.py -p Wikipedia_Page_Article_Here
import pandas as pd
import argparse
import wikipedia as wp
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--wiki_page", help="Give a wiki page to get table", required=True)
args = parser.parse_args()
html = wp.page(args.wiki_page).html().encode("UTF-8")
try: 
    df = pd.read_html(html)[1]  # Try 2nd table first as most pages contain contents table first
except IndexError:
    df = pd.read_html(html)[0]
print(df.to_string())

希望这可以帮助那里的人!

关于python-3.x - 有选择地使用 Python 抓取维基百科表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50355577/

相关文章:

python - 需要使用 RegEx 和 BeautifulSoup 查找文本

python - 来自 2500 个链接的网页抓取 - 行动方案?

python - 在python中使用bs4从网站的不同链接获取律师详细信息

Python 在写入文件时处理换行符和制表符

python - 导入错误: cannot import name 'LatentDirichletAllocation'

python-3.x - python 列表中的冲突案例

python - HTTP 错误 504 : Gateway Time-out when trying to read a reddit comments post

javascript - 以字符串格式在页面源上执行 javascript 选择器

beautifulsoup - 安装了 BeautifulSoup 但仍然没有得到名为 bs4 的模块

python - 2to3 进行多次导入