答案页 · 12 道题

Python 爬虫 HTTP 请求练习答案

本页汇总 Python 爬虫 HTTP 请求 的 12 道练习。先做练习页,再回到这里核对准确答案和原因。

快速答案

本答案页包含 Python 爬虫 HTTP 请求 的 4 道选择题、4 道填空题和 4 道输出预测题,每题都给出准确答案和简短解释。

答案已完整展示,建议先尝试作答,再用本页核对。第一次练习最好从互动练习页开始。

01 · 选择题

User-Agent 请求头用来标识什么?

  1. 发起请求的客户端正确答案
  2. 页面的 CSS 文件
  3. 响应编码
  4. 服务器数据库

答案: 发起请求的客户端

为什么: 描述清楚的 User-Agent 告诉服务器是哪个客户端在访问。

02 · 选择题

为什么要给请求设置超时?

  1. 跳过 robots.txt
  2. 让 HTML 变合法
  3. 避免卡住的连接一直挂起正确答案
  4. 压缩图片

答案: 避免卡住的连接一直挂起

为什么: 超时限制客户端等待多久后放弃。

03 · 选择题

哪个状态码表示请求成功?

  1. 200正确答案
  2. 301
  3. 404
  4. 500

答案: 200

为什么: 2xx 状态码表示成功;200 是最常见的 OK 响应。

04 · 选择题

运行结果是什么?

from urllib.request import Request
request = Request("https://example.com/docs", headers={"User-Agent": "PyPracticeBot/1.0"})
print(request.get_header("User-agent"))
  1. PyPracticeBot/1.0正确答案
  2. docs
  3. example.com
  4. None

答案: PyPracticeBot/1.0

为什么: get_header 返回 User-Agent 请求头中保存的值。

05 · 填空题

补全 Request 的导入。

from urllib.request import ____

答案: Request

为什么: Request 用来构造请求对象,不会立即发送。

06 · 填空题

补全保存请求头的关键字参数。

from urllib.request import Request
request = Request("https://example.com", ____={"User-Agent": "Bot/1.0"})
print(request.get_header("User-agent"))

答案: headers

为什么: headers 映射会传给 Request 构造函数。

07 · 填空题

补全 2xx 成功状态码的上界。

status = 204
print(200 <= status < ____)

答案: 300

为什么: 成功响应是 200 到 299,所以不包含的上界是 300。

08 · 填空题

补全标识客户端的请求头名称。

from urllib.request import Request
request = Request("https://example.com", headers={"____": "LearningBot/1.0"})
print(request.get_header("User-agent"))

答案: User-Agent

为什么: User-Agent 是标识客户端的标准请求头。

09 · 输出预测

这段程序打印出什么?

from urllib.request import Request
request = Request("https://example.com/a?x=1")
print(request.full_url)

答案: https://example.com/a?x=1

为什么: full_url 返回请求中保存的完整 URL。

10 · 输出预测

代码的输出结果是什么?

from urllib.request import Request
request = Request("https://example.com", headers={"User-Agent": "MyBot/1.0"})
print(request.get_header("User-agent"))

答案: MyBot/1.0

为什么: 请求头查询返回 headers 映射中提供的值。

11 · 输出预测

屏幕上会显示什么?

status = 404
print("ok" if 200 <= status < 300 else "error")

答案: error

为什么: 404 不在 2xx 成功范围内,所以条件表达式输出 error。

12 · 输出预测

这段代码会输出什么?

status = 429
print("retry" if status == 429 else "go")

答案: retry

为什么: 429 表示请求过多,所以输出 retry。

先试一遍题目

打开 Python 爬虫 HTTP 请求 练习页,用即时反馈回答同样的 12 道题。

练习本课