开始使用免费开始使用

体验 Wikipedia API

您做得很棒,也玩得很开心,我们再给您一个 API:Wikipedia API(文档见此处)。您将学习如何从 Wikipedia 的"Pizza"页面查找并提取信息。这里稍微有点复杂:您的查询会返回"嵌套"的 JSON,也就是 JSON 里面再包含 JSON。但 Python 可以处理,因为它会把它们转换为"字典中的字典"。

从 Wikipedia API 请求相关查询的 URL 是:

https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=pizza

本练习是课程的一部分

Python 数据导入进阶

查看课程

练习说明

  • 将相应的 URL 赋值给变量 url
  • 对响应对象 r 调用 json() 方法,并将得到的字典保存到变量 json_data 中。
  • 变量 pizza_extract 保存了 Wikipedia"Pizza"页面的一段内容的 HTML 字符串;使用函数 print() 将该字符串打印到控制台。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import package
import requests

# Assign URL to variable: url


# Always include a descriptive User-Agent (Wikipedia requires this)
headers = {
    "User-Agent": "Checking out the Wikipedia API"
}

# Package the request, send the request and catch the response: r
r = requests.get(url, headers=headers)

# Decode the JSON data into a dictionary: json_data


# Print the Wikipedia page extract
pizza_extract = json_data['query']['pages']['24768']['extract']
____
编辑并运行代码