Python网络请求教程_requests库使用全解析

11次阅读

requests 是 python 最常用、最友好的 http 客户端库,一行安装、一行发送 GET 请求,支持参数传递、jsON 提交、自定义请求头、异常处理、会话管理、超时控制和流式文件下载。

Python网络请求教程_requests库使用全解析

requests 是 Python 最常用、最友好的 HTTP 客户端库,它让发送网络请求像调用函数一样简单。掌握它,就能轻松完成网页抓取、API 调用、文件下载等绝大多数网络交互任务。

安装与基础请求

使用 pip 一行安装:

pip install requests

发送最简单的 GET 请求只需一行代码:

立即学习Python免费学习笔记(深入)”;

response = requests.get(“https://httpbin.org/get”)

返回的 response 对象包含状态码、响应头、文本内容等关键信息。常用属性有:

  • response.status_code:HTTP 状态码(如 200、404)
  • response.text:响应体的字符串(自动按响应头编码解码)
  • response.json():若响应是合法 json,直接解析为 Python 字典或列表
  • response.headers:响应头字典,例如 response.headers[“Content-Type”]

传参与请求头设置

GET 请求的 URL 参数可直接用 params 参数传入字典,requests 自动拼接并编码

requests.get(“https://httpbin.org/get”, params={“name”: “张三”, “age”: 25})

POST 提交表单数据常用 data 参数(自动编码为 application/x-www-form-urlencoded):

requests.post(“https://httpbin.org/post”, data={“user”: “admin”, “pwd”: “123”})

若需提交 JSON,推荐用 json 参数(自动序列化 + 设置 Content-Type: application/json):

requests.post(“https://httpbin.org/post”, json={“id”: 1, “title”: “Hello”})

自定义请求头(如模拟浏览器访问、携带 Token)用 headers 参数:

headers = {“User-Agent”: “Mozilla/5.0…”, “Authorization”: “Bearer xxx”}
requests.get(“https://api.example.com/data”, headers=headers)

处理响应与异常

别直接假设请求一定成功。建议先检查状态码:

if response.status_code == 200:
  data = response.json()
else:
 &nbsp>print(f”请求失败,状态码:{response.status_code}”)

更稳妥的方式是使用 raise_for_status(),它会在非 2xx 状态时主动抛出 requests.exceptions.HTTPError

try:
  response = requests.get(url)
 &nbsp>response.raise_for_status()
  data = response.json()
except requests.exceptions.RequestException as e:
  print(“网络请求出错:”, e)

常见异常类型包括:ConnectionError(连接失败)、Timeout(超时)、HTTPError(HTTP 错误响应)。

会话管理与进阶技巧

需要保持登录态、复用连接或共享 cookies 时,用 requests.session()

session = requests.Session()
session.post(“https://example.com/login”, data=login_data)
res = session.get(“https://example.com/profile”) # 自动携带登录 cookie

控制超时避免卡死(单位:秒),推荐始终设置:

  • timeout=5:总耗时不超过 5 秒(连接 + 响应)
  • timeout=(3, 7):连接最多 3 秒,响应最多 7 秒

下载文件时,用 stream=True 防止大文件一次性加载到内存:

with requests.get(url, stream=True) as r:
  r.raise_for_status()
  with open(“file.pdf“, “wb”) as f:
    for chunk in r.iter_content(chunk_size=8192):
      f.write(chunk)

text=ZqhQzanResources