← 返回知识宇宙
python常用工具·进阶

HTTP 请求库 Requests 演示教程:从一次 GET 到稳健的下载客户端

本文通过 httpbin.org 实操演示 Python requests 库的 GET、POST、PUT、查询参数、请求头、状态码与异常、超时、会话 Session 和 HTTP 基本认证,最后编写一个带会话与超时的稳健客户端下载 pandas 官方泰坦尼克数据集。

知识编号06
关系轨道4
学习难度进阶
RequestsHTTPPython网络请求API入门教程
哔哩哔哩

视频讲解

HTTP 请求库 Requests 演示教程:从一次 GET 到稳健的下载客户端

这不是讲概念的讲义,而是一套跟着屏幕敲的演示脚本。我们用 requests 作者官方维护的测试站 httpbin.org,把{{GET}}、{{POST}}、{{查询参数}}、{{请求头}}、{{状态码}}、{{超时}}、{{会话}}、{{认证}}全部走一遍,最后写一个能下载官方数据集的稳健客户端,亲眼看懂一次 HTTP 请求的每一步。

准备环境:macOS / Linux / Windows WSL 均可,需要 python3(3.14)与已装好的 requests,用 python3 -c "import requests;print(requests.version)" 验证;演示对象是 requests 官方维护的 httpbin.org,数据集来自 pandas 官方仓库,均需联网。

Demo 1:一个 GET 打过去,拿到 JSON 和状态码

Screen

终端打印四行:状态码 200、内容类型 application/json、请求 URL、以及服务器看到的 User-Agent。

Command

python3 - <<'PY'
import requests
r = requests.get("https://httpbin.org/get")
print("状态码:", r.status_code)
print("内容类型:", r.headers["Content-Type"])
data = r.json()
print("请求 URL:", data["url"])
print("服务器看到我的 UA:", data["headers"]["User-Agent"])
PY

Output

状态码: 200
内容类型: application/json
请求 URL: https://httpbin.org/get
服务器看到我的 UA: python-requests/2.33.1

Narration

requests 的第一个命令就是 get。一个网址进去,返回一个 Response 对象,status_code 是 200 表示成功,headers 里 Content-Type 是 application/json 说明返回的是 JSON。r.json() 直接把它解析成 Python 字典。看服务器看到我的 UA 是 python-requests/2.33.1——每个请求都会自动带上这个身份标识。这串 UA 还会被反爬识别,想改它也得先知道它在哪。

Demo 2:Response 对象:text 与 content 的区别

Screen

终端打印五样:状态码 200、编码 utf-8、Server 头 gunicorn、内容类型、内容字节数 314。

Command

python3 - <<'PY'
import requests
r = requests.get("https://httpbin.org/get")
print("状态码:", r.status_code)
print("编码:", r.encoding)
print("Server 头:", r.headers.get("Server"))
print("内容类型:", r.headers.get("Content-Type"))
print("内容字节数:", len(r.content))
PY

Output

状态码: 200
编码: utf-8
Server 头: gunicorn/19.9.0
内容类型: application/json
内容字节数: 314

Narration

Response 对象里藏着很多信息。encoding 是它猜的文本编码,headers 是响应头,len(r.content) 是字节数。这里要点出 text 和 content 的区别:text 是解码后的字符串,content 是原始字节。下载文件、图片时一定要用 content,用 text 会破坏二进制数据——这是新手下载文件最常踩的坑,记住了就避开一大半乱码问题。

Demo 3:params 字典:参数自动拼进 URL

Screen

终端打印完整 URL(末尾带 name=jason 和 page=2)和服务器解析回显的 args 字典。

Command

python3 - <<'PY'
import requests
r = requests.get("https://httpbin.org/get", params={"name": "jason", "page": 2})
data = r.json()
print("完整 URL:", data["url"])
print("解析出的参数:", data["args"])
PY

Output

完整 URL: https://httpbin.org/get?name=jason&page=2
解析出的参数: {'name': 'jason', 'page': '2'}

Narration

想带参数怎么办?params 字典帮你自动拼到 URL 上。name=jason 和 page=2 变成了问号后面的一串,httpbin 把它原样解析回 args 字典回显给你。注意参数都是字符串,所以 page 是 '2' 不是数字 2——这是 GET 请求的规矩,参数永远以字符串在 URL 里传递,要传数字得先转成字符串。

Demo 4:POST 加 json:把字典发到服务器

Screen

终端打印状态码 200 和服务器收到的 JSON 字典(title 和 views)。

Command

python3 - <<'PY'
import requests
r = requests.post("https://httpbin.org/post", json={"title": "Python 教程", "views": 100})
data = r.json()
print("状态码:", r.status_code)
print("服务器收到的 JSON:", data["json"])
PY

Output

状态码: 200
服务器收到的 JSON: {'title': 'Python 教程', 'views': 100}

Narration

发送数据用 POST。json 参数把字典序列化成 JSON 放进请求体,httpbin 把它原样回显在 json 字段里。以后调 API、提交数据,POST 加 json 是最常见的组合。记住一句话:GET 是取数据,POST 是交数据,方向不能搞反,搞反了轻则拿不到数据,重则误改线上数据。

Demo 5:PUT 加表单和自定义请求头

Screen

终端打印三行:状态码 200、收到的表单字典 key=value、以及自定义头 X-Custom 的值 hello。

Command

python3 - <<'PY'
import requests
r = requests.put("https://httpbin.org/put", data={"key": "value"}, headers={"X-Custom": "hello"})
data = r.json()
print("状态码:", r.status_code)
print("收到的表单:", data["form"])
print("自定义头:", data["headers"]["X-Custom"])
PY

Output

状态码: 200
收到的表单: {'key': 'value'}
自定义头: hello

Narration

HTTP 还有一堆别的动词,put 是更新、delete 是删除,这里用 put 演示。data 参数发的是{{表单}}格式,headers 能加自定义请求头,X-Custom 这个自定义头被 httpbin 原样收下。真实项目里加鉴权 token、加链路追踪 ID,靠的都是自定义头。自定义头本身不校验,但约定的格式还是要跟对。

Demo 6:状态码与异常:404、500、raise_for_status

Screen

终端打印 404 状态码和 ok=False,再打印捕获到的 500 异常信息。

Command

python3 - <<'PY'
import requests
r = requests.get("https://httpbin.org/status/404")
print("404 请求状态码:", r.status_code, "ok?", r.ok)
try:
    requests.get("https://httpbin.org/status/500").raise_for_status()
except requests.HTTPError as e:
    print("捕获到:", e)
PY

Output

404 请求状态码: 404 ok? False
捕获到: 500 Server Error: INTERNAL SERVER ERROR for url: https://httpbin.org/status/500

Narration

不是所有请求都成功。404 是找不到,r.ok 是 False。更省事的做法是 raise_for_status()——状态码是 4xx 或 5xx 时直接抛异常,500 是服务器内部错误,被我们捕获打印出来。生产代码里这一步必须做,否则一个失败请求会静默地带着半截数据往下跑,酿成更难查的 bug。异常处理不是可选项,是基本盘。

Demo 7:超时:不给 timeout,程序可能永远卡死

Screen

终端先打印超时捕获的那句话,再打印快速请求的状态码 200。

Command

python3 - <<'PY'
import requests
try:
    requests.get("https://httpbin.org/delay/3", timeout=1)
except requests.Timeout:
    print("请求超时了(1 秒内没回来)")
print("快速请求状态码:", requests.get("https://httpbin.org/get", timeout=5).status_code)
PY

Output

请求超时了(1 秒内没回来)
快速请求状态码: 200

Narration

网络是会卡死的,所以必须设{{超时}}。给 delay/3 这个故意慢 3 秒的接口设 1 秒超时,立刻抛 Timeout 被捕获。第二个正常请求设 5 秒超时,毫秒级返回。永远不要裸奔发请求——不设 timeout,你的程序可能永远卡在等一个不响应的服务器。设超时,是写给自己的救命稻草,多少线上事故都是没设超时闹的。

Demo 8:会话 Session:自动记住 cookie

Screen

终端打印会话里的 cookie 字典,flavor 的值是 chocolate。

Command

python3 - <<'PY'
import requests
s = requests.Session()
s.get("https://httpbin.org/cookies/set?flavor=chocolate")
r = s.get("https://httpbin.org/cookies")
print("会话里的 cookie:", r.json()["cookies"])
PY

Output

会话里的 cookie: {'flavor': 'chocolate'}

Narration

{{会话 Session}} 帮你记住跨请求的状态。先访问 cookies/set 让服务器种下一个 flavor=chocolate 的 cookie,再用同一个 session 访问 /cookies,cookie 自动被带回来。要登录后保持身份、要在一串请求里维持 token,就用 Session,它省掉你手动管理 cookie 的麻烦,它内部还复用了连接池,跑起来更快。

Demo 9:HTTP 基本认证:auth 元组一把过

Screen

终端打印两行:正确密码返回状态码 200 和认证成功的字典,错误密码返回状态码 401。

Command

python3 - <<'PY'
import requests
r = requests.get("https://httpbin.org/basic-auth/jason/secret", auth=("jason", "secret"))
print("正确密码状态码:", r.status_code)
print("返回:", r.json())
r2 = requests.get("https://httpbin.org/basic-auth/jason/secret", auth=("jason", "wrong"))
print("错误密码状态码:", r2.status_code)
PY

Output

正确密码状态码: 200
返回: {'authenticated': True, 'user': 'jason'}
错误密码状态码: 401

Narration

很多接口要登录,{{HTTP 基本认证}}是最老的一种。auth 传一个用户名密码元组,requests 自动把它编码进请求头。正确密码返回 200 和 authenticated=true,错误密码返回 401。记住 401 就是未授权,看到它先检查凭证对不对。基本认证明文传输,正式项目请换 token 或 OAuth,这点心里要有数。

Demo 10:下载字节:content 拿到完整字节流

Screen

终端打印三行:状态码 200、下载字节数 1024、Content-Length 头 1024。

Command

python3 - <<'PY'
import requests
r = requests.get("https://httpbin.org/bytes/1024")
print("状态码:", r.status_code)
print("下载字节数:", len(r.content))
print("Content-Length 头:", r.headers.get("Content-Length"))
PY

Output

状态码: 200
下载字节数: 1024
Content-Length 头: 1024

Narration

下载文件用 content。bytes/1024 这个接口返回 1024 个字节,len(r.content) 正好 1024,Content-Length 头也写的是 1024,三者对上了。真实下载大文件时要分块写入、边下边存,但这里先体会 content 拿到的是完整字节流,而不是被解码破坏的字符串。下一段就用它下载一份真实数据,看看完整闭环。

Final Practical Project:稳健小客户端:会话加超时,下载官方数据集

Screen

终端先打印 httpbin 健康检查状态 200,再打印下载字节数 60080、总行数 892、表头一行、第一行数据。

Command

python3 - <<'PY'
import requests
s = requests.Session()
health = s.get("https://httpbin.org/get", timeout=10)
print("httpbin 状态:", health.status_code)
url = "https://raw.githubusercontent.com/pandas-dev/pandas/main/doc/data/titanic.csv"
r = s.get(url, timeout=15)
lines = r.text.strip().splitlines()
print("下载字节数:", len(r.content))
print("总行数(含表头):", len(lines))
print("表头:", lines[0])
print("第一行数据:", lines[1])
PY

Output

httpbin 状态: 200
下载字节数: 60080
总行数(含表头): 892
表头: PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked
第一行数据: 1,0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S

Narration

最后写一个稳健的小客户端:用 Session 先做一次健康检查,再下载 pandas 官方的泰坦尼克数据集。60080 个字节、892 行,表头是第一行,第一行数据是 Owen Harris 先生。带超时、带会话、直接解析文本——这就是 requests 在真实数据管道里的样子,后面任何爬虫、任何调 API 的脚本,都是这个骨架。

实践示例

更多python常用工具知识