使用Python访问维基百科API的JSON数据

2 投票
2 回答
4582 浏览
提问于 2025-04-18 08:07

我想用一个来自维基百科API的JSON文件,制作一个包含文森特·梵高所有画作的Python列表。这里是我用来发送请求的链接:

http://en.wikipedia.org/w/api.php?format=json&action=query&titles=list%20of%20works%20by%20Vincent%20van%20Gogh&Page&prop=revisions&rvprop=content

如果你在浏览器中打开这个链接,你会看到一大堆文字。那我该怎么开始从这个庞大的JSON返回中提取画作的标题呢?在问这个问题之前,我已经做了很多研究,并尝试了很多方法来解决这个问题。如果这个JSON文件能像一个有用的字典那样好用就好了,但我实在搞不懂它。你会怎么从这个JSON文件中提取画作的名字呢?

2 个回答

0

这里有一个快速的方法,可以把你的列表放到一个熊猫数据框里。

import pandas as pd
url = 'http://en.wikipedia.org/wiki/List_of_works_by_Vincent_van_Gogh'
df = pd.read_html(url, attrs={"class": "wikitable"})[0] # 0 is for the 1st table in this particular page
df.head()
6

与其直接解析JSON API调用的结果,不如使用一个Python封装库来处理。

import wikipedia

page = wikipedia.page("List_of_works_by_Vincent_van_Gogh")
print page.links

还有其他的客户端和封装库可以选择。

另外,你也可以使用BeautifulSoup这个HTML解析器来实现:

>>> from bs4 import BeautifulSoup
>>> url = "http://en.wikipedia.org/wiki/List_of_works_by_Vincent_van_Gogh"
>>> soup = BeautifulSoup(urlopen(url))
>>> table = soup.find('table', class_="wikitable")
>>> for row in table.find_all('tr')[1:]:
...     print(row.find_all('td')[1].text)
... 
Still Life with Cabbage and Clogs
Crouching Boy with Sickle, Black chalk and watercolor
Woman Sewing, Watercolor
Woman with White Shawl
...

撰写回答