requests 是 Python 最常用的 HTTP 客户端库,以“简单、优雅”著称。它封装了底层的 urllib3,让你用非常 Pythonic 的方式发送 HTTP 请求。

1. 安装

pip install requests

2. 基本用法

🔹 GET 请求

import requests

url = "https://httpbin.org/get"
params = {"q": "python", "page": 1}

resp = requests.get(url, params=params)

print(resp.status_code)
print(resp.json())

要点

  • params 会自动拼接到 URL 上

  • resp.json() 自动解析 JSON

🔹 POST 请求(表单)

data = {"username": "doudou", "password": "123456"}
resp = requests.post("https://httpbin.org/post", data=data)
print(resp.json())

🔹 POST 请求(JSON)

payload = {"name": "doudou", "age": 18}
resp = requests.post("https://httpbin.org/post", json=payload)
print(resp.json())

json= 会自动设置 Content-Type: application/json

3. 常用参数

🔹 Headers

headers = {
    "User-Agent": "Mozilla/5.0",
    "Authorization": "Bearer xxx"
}
resp = requests.get(url, headers=headers)

🔹 Cookies

cookies = {"sessionid": "abcd1234"}
resp = requests.get(url, cookies=cookies)

🔹 超时 timeout(强烈建议生产环境必须加)

resp = requests.get(url, timeout=5)
  • timeout=5 表示最多等待 5 秒

  • 不加 timeout 会导致程序卡死

🔹 禁用 SSL 证书验证(不推荐)

resp = requests.get(url, verify=False)

4. 上传文件

files = {
    "file": ("test.txt", open("test.txt", "rb"), "text/plain")
}

resp = requests.post("https://httpbin.org/post", files=files)
print(resp.json())

5. 下载文件(流式)

resp = requests.get(url, stream=True)

with open("image.png", "wb") as f:
    for chunk in resp.iter_content(chunk_size=1024):
        f.write(chunk)

6. Session 会话(保持 Cookie、Header)

企业级项目中非常常用。

session = requests.Session()

session.headers.update({"User-Agent": "Mozilla/5.0"})

# 第一次请求会保存 cookie
session.get("https://httpbin.org/cookies/set/sessionid/123456")

# 第二次请求自动带 cookie
resp = session.get("https://httpbin.org/cookies")
print(resp.json())

7. 处理响应

resp = requests.get(url)

resp.status_code      # 状态码
resp.text             # 文本内容
resp.content          # 二进制内容
resp.json()           # JSON
resp.headers          # 响应头
resp.cookies          # Cookie

8. 错误处理(企业级必备)

import requests

try:
    resp = requests.get(url, timeout=5)
    resp.raise_for_status()  # 自动抛出 4xx/5xx 错误
except requests.exceptions.Timeout:
    print("请求超时")
except requests.exceptions.HTTPError as e:
    print("HTTP 错误:", e)
except requests.exceptions.RequestException as e:
    print("请求失败:", e)

9. 代理(常用于爬虫或企业内网)

proxies = {
    "http": "http://127.0.0.1:7890",
    "https": "http://127.0.0.1:7890",
}

resp = requests.get(url, proxies=proxies)

10. 企业级最佳实践(你会喜欢)

✔ 必须设置 timeout

避免接口挂死导致线程阻塞。

✔ 使用 Session 复用连接

减少 TCP 握手,提高性能。

✔ 使用 raise_for_status()

自动捕获 4xx/5xx。

✔ 日志记录请求与响应

方便排查问题。

✔ 对外部 API 做重试机制

可结合 urllib3.util.retry

11. 完整企业级请求封装示例

import requests

class HttpClient:
    def __init__(self, base_url):
        self.session = requests.Session()
        self.base_url = base_url
        self.session.headers.update({
            "User-Agent": "Mozilla/5.0",
            "Accept": "application/json"
        })

    def request(self, method, path, **kwargs):
        url = self.base_url + path
        try:
            resp = self.session.request(method, url, timeout=5, **kwargs)
            resp.raise_for_status()
            return resp.json()
        except requests.exceptions.RequestException as e:
            print("请求失败:", e)
            return None

client = HttpClient("https://httpbin.org")

print(client.request("GET", "/get", params={"a": 1}))

这段代码可以直接用于企业项目。

Logo

这里是“一人公司”的成长家园。我们提供从产品曝光、技术变现到法律财税的全栈内容,并连接云服务、办公空间等稀缺资源,助你专注创造,无忧运营。

更多推荐