Menu
CoddyTech

处理 requests 响应

Coddy Python 中的 API 课程的第 7 课,共 10 课。

通过 API 调用 get() 或 post() 后,你会收到一个 response 对象,我们在前面的示例中将它存储在 response 变量中。


正如我们在 JSON 课中学到的,这些响应采用 JSON 格式或 Python 原生的字典格式。

 

要获取响应的 JSON 格式,你需要这样写:

data = response.json()

然后,你可以使用字典的键访问方法,解析响应中需要的值。

challenge icon

挑战

中等

说明:

  1. 发送 GET 请求到:https://jsonplaceholder.typicode.com/users/1
  2. 将 requests.get() 对象保存到名为 response 的变量中
  3. 解析 response.json(),并将结果保存到名为 data 的变量中
  4. 使用键访问方式将 data["name"] 保存到名为 result 的变量中
  5. 打印 result,它应始终显示:Leanne Graham

亲手试试

import requests

# Step 1: Send GET request
response = # Your code here

# Step 2: Parse JSON response
data = # Your code here

# Step 3: Get the name
result = # Your code here

# Step 4: Print the result
print(result)

Python 中的 API中的所有课

自己练习: Python 在线编译器