开始使用免费开始使用

使用 urllib 发起 API 请求

在本课程中,您将使用一个音乐目录(Music Catalog)应用的 API。该 API 提供多种功能。您将从 Lyrics API 开始,它可以获取"每日歌词"中的一句歌词。

在发出第一个 API 请求之前,您需要知道该 API 的访问地址。这一地址也称为 URL(Uniform Resource Locator,统一资源定位符)。URL 会告诉 Python 将 API 请求发送到"哪里"。Lyrics API 的 URL 如下:http://localhost:3000/lyrics/

现在就用内置的 Python 模块 urllib 向 Lyrics API 发起第一个请求。

本练习是课程的一部分

Python 中的 API 入门

查看课程

练习说明

  • 在响应对象上使用 read 函数,从响应对象中读取响应数据。
  • 使用 decode 函数,结合正确的编码将响应数据解码为字符串。

交互式实操练习

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

from urllib.request import urlopen

with urlopen('http://localhost:3000/lyrics/') as response:
  
  # Use the correct function to read the response data from the response object
  data = response.____()
  encoding = response.headers.get_content_charset()

  # Decode the response data so you can print it as a string later
  string = data.____(encoding)
  
  print(string)
编辑并运行代码