我有一个看起来像这样的程序:
import json
import requests
article_name = "BT Centre"
article_api_url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles={}".format(article_name)
called_data = requests.get(article_api_url)
formatted_data = called_data.json()
print(formatted_data)
pages = formatted_data["query"]["pages"]
print(pages)
first_page = pages[0]["extract"]
print(first_page)
对于第一个打印语句,它打印整个 JSON,它返回这个:
{
'batchcomplete': '','query':{
'pages':{
'18107207':{
'pageid': 18107207,'ns': 0,'title':'BT Centre','extract': "The BT Centre is the global headquarters and registered office of BT Group..."
}
}
}
}
当我尝试使用 first_page
变量访问“提取”数据时,它返回:
Traceback (most recent call last):
File "wiki_json_printer.py",line 15,in <module>
first_page = pages[0]["extract"]
KeyError: 0
问题是,我无法将 first_page
设置为 pages["18107207"]["extract"]
,因为每篇文章的页面 ID 都会发生变化。
编辑:来自 Ann Zen 作品的解决方案:
您可以使用 for 循环来遍历页面的键 字典,并通过 str.isdigit() 检测哪个是 ID 方法:
for key in pages:
if key.isdigit():
print(pages[key]["extract"])