现代应用几乎都离不开网络:调第三方 API、抓取公开数据、上传文件。Python 的 requests 库把 HTTP 请求封装得极其优雅,几行代码就能完成 GET/POST 请求。本文带你从零掌握它。

1. 安装与第一个请求

requests 不是标准库,先安装再使用:

pip install requests
import requests

resp = requests.get("https://httpbin.org/get")
print(resp.status_code)   # 200
print(resp.json())        # 自动解析 JSON 响应

2. 常用参数

查询参数、请求头、超时时间,一次请求全部搞定:

import requests

params = {"q": "python", "page": 2}
headers = {"User-Agent": "Mozilla/5.0"}
resp = requests.get(
    "https://api.example.com/search",
    params=params, headers=headers, timeout=10,
)
print(resp.url)  # 实际请求的完整 URL

timeout 务必设置,否则请求可能无限挂起。

3. POST 与 JSON 数据

提交 JSON 用 json= 参数,requests 会自动设置 Content-Type 并完成序列化:

import requests

payload = {"username": "ada", "password": "secret"}
resp = requests.post("https://httpbin.org/post", json=payload)
print(resp.json()["json"])  # 回显提交的数据

4. 状态码与异常处理

网络请求必然要处理失败,标准姿势是 raise_for_status() 加捕获异常:

import requests

try:
    resp = requests.get("https://httpbin.org/status/404", timeout=5)
    resp.raise_for_status()   # 4xx/5xx 会抛出异常
except requests.RequestException as e:
    print("请求失败:", e)

5. 实战:查询天气 API

用免费的 Open-Meteo 接口查询北京近几日最高气温:

import requests

url = "https://api.open-meteo.com/v1/forecast"
params = {
    "latitude": 39.9,
    "longitude": 116.4,
    "daily": "temperature_2m_max",
    "timezone": "Asia/Shanghai",
}
data = requests.get(url, params=params, timeout=10).json()
print(data["daily"]["temperature_2m_max"])  # [33.2, 31.5, ...]

6. Session 与注意事项

💡 学习建议:注册一个免费 API(天气、汇率、随机笑话都行),写脚本定时拉取数据存到本地,多练几次就熟了。动手前先读 API 文档里的限流规则。