使用 requests 包
使用 urllib 集成 API 往往会让代码变得冗长且复杂,因为您需要处理很多额外事项,例如对响应进行编码和解码。
作为 urllib 的替代方案,Python 的 requests 包提供了更简单的 API 集成方式。许多功能在 requests 中开箱即用,使代码更易写、更易读。现在我们用 requests 包再做一遍同样的练习。
请记住,与上一个练习相同,Lyrics API 的 URL 为 http://localhost:3000/lyrics。
本练习是课程的一部分
Python 中的 API 入门
练习说明
- 导入
requests包。 - 将 URL
http://localhost:3000/lyrics传给requests.get方法。 - 打印响应文本。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import the requests package
import ____
# Pass the API URL to the get function
response = requests.get(____)
# Print out the text attribute of the response object
print(response.____)