杰瑞科技汇

Python requests参数有哪些?如何使用?

基本语法

requests() 函数的基本语法如下:

import requests
response = requests.method(url, params=None, data=None, json=None, headers=None, cookies=None, auth=None, files=None, timeout=None, allow_redirects=True, proxies=None, verify=None, stream=None, cert=None)

method 是 HTTP 方法,如 get(), post(), put(), delete() 等,这些方法(如 requests.get())本质上是 requests.request('get', ...) 的快捷方式,它们共享完全相同的参数。

下面我们分类详细介绍这些参数。


URL (url)

  • 类型: str
  • 描述: 发送请求的目标 URL,这是唯一一个必须提供的位置参数。
  • 示例:
    response = requests.get('https://www.example.com/api/users/1')

查询参数 (params)

  • 类型: dictbytes

  • 描述: 用于向 URL 添加查询字符串(Query String),即 URL 中 后面的 key=value 对。requests 会自动对其进行 URL 编码,你无需手动处理。

  • 示例:

    # 字典形式
    payload = {'key1': 'value1', 'key2': 'value2'}
    response = requests.get('https://httpbin.org/get', params=payload)
    # 最终请求的 URL 会是: https://httpbin.org/get?key1=value1&key2=value2
    print(response.url)

请求体数据 (datajson)

这是 POST, PUT, PATCH 等请求最常用的参数,用于发送请求体数据。

data

  • 类型: dict, list of tuples, bytes, 或 file-like object
  • 描述: 用于发送表单数据,当传入一个字典时,requests 会将其编码为 application/x-www-form-urlencoded 格式。
  • 适用场景: 传统 HTML 表单提交。
  • 示例:
    payload = {'username': 'john', 'password': 'secret'}
    response = requests.post('https://httpbin.org/post', data=payload)
    # 服务器会收到 Content-Type: application/x-www-form-urlencoded 的数据

json

  • 类型: dict 或其他可被 json.dumps() 序列化的对象
  • 描述: 用于发送 JSON 格式的数据。requests 会自动将 Python 对象序列化为 JSON 字符串,并设置 Content-Type 请求头为 application/json
  • 适用场景: RESTful API 交互,现代 Web 服务。
  • 示例:
    payload = {'name': 'Alice', 'age': 30, 'city': 'New York'}
    response = requests.post('https://httpbin.org/post', json=payload)
    # 服务器会收到 Content-Type: application/json 的数据,数据为 '{"name": "Alice", "age": 30, "city": "New York"}'

请求头 (headers)

  • 类型: dict
  • 描述: 用于自定义 HTTP 请求头,可以覆盖 requests 自动设置的默认头(如 User-Agent)。
  • 常见用途:
    • 设置 Content-Type(如果不想用 jsondata 的默认值)。
    • 设置 Accept 告诉服务器你期望接收的数据格式。
    • 设置认证 Token(如 Authorization: Bearer <token>)。
  • 示例:
    headers = {
        'User-Agent': 'MyCoolApp/1.0',
        'Accept': 'application/json',
        'Authorization': 'Bearer your_api_token_here'
    }
    response = requests.get('https://api.github.com/user', headers=headers)

Cookies (cookies)

  • 类型: dict
  • 描述: 用于在请求中发送 cookies,字典的键是 cookie 的名称,值是 cookie 的值。
  • 示例:
    cookies = {'session_id': '1234567890', 'user_pref': 'dark_mode'}
    response = requests.get('https://httpbin.org/cookies', cookies=cookies)

身份验证 (auth)

  • 类型: tuplerequests.auth.AuthBase 的实例
  • 描述: 用于 HTTP 基本身份验证,最简单的方式是传入一个 (username, password) 元组。
  • 示例:
    # 基本身份验证
    from requests.auth import HTTPBasicAuth
    # 或者直接使用元组
    response = requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))

文件上传 (files)

  • 类型: dict
  • 描述: 用于向服务器上传文件,字典的键是表单字段的名称,值是一个文件元组 (filename, file_object, content_type)
  • 示例:
    with open('report.xlsx', 'rb') as f:
        files = {
            'file': ('report.xlsx', f, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        }
        response = requests.post('https://httpbin.org/post', files=files)

超时 (timeout)

  • 类型: float, tuple

  • 描述: 设置请求的超时时间,防止程序无限等待,这是一个非常重要的参数!

    • 单个浮点数(如 timeout=5.0):表示连接和读取的总超时时间。
    • 元组(如 timeout=(3.05, 27)):(连接超时, 读取超时)`,连接超时是服务器建立连接的最长时间;读取超时是从服务器读取数据的最长时间。
  • 示例:

    # 总超时时间为 5 秒
    response = requests.get('https://httpbin.org/delay/10', timeout=5) # 这会抛出 requests.exceptions.Timeout 异常
    # 连接超时 3 秒,读取超时 10 秒
    response = requests.get('https://httpbin.org/delay/10', timeout=(3, 10))

代理 (proxies)

  • 类型: dict
  • 描述: 用于设置代理服务器,帮助你绕过网络限制或进行匿名访问。
  • 示例:
    proxies = {
        'http': 'http://10.10.1.10:3128',
        'https': 'http://10.10.1.10:1080',
    }
    response = requests.get('https://httpbin.org/ip', proxies=proxies)

SSL 证书验证 (verify)

  • 类型: boolstr

  • 描述: 控制 SSL 证书验证。

    • True (默认): 验证服务器的 SSL 证书。
    • False: 禁用验证,不安全,仅用于测试。
    • str: 指定 CA_BUNDLE 文件的路径或目录,用于自定义证书验证。
  • 示例:

    # 禁用 SSL 验证(不推荐在生产环境中使用)
    response = requests.get('https://httpbin.org/get', verify=False)
    # 使用自定义的 CA 证书
    response = requests.get('https://httpbin.org/get', verify='/path/to/certfile.pem')

流式下载 (stream)

  • 类型: bool

  • 描述: 控制是否立即下载响应内容。

    • False (默认): 立即下载整个响应体到内存。
    • True: 延迟下载,直到你调用 response.contentresponse.iter_content(),这对于下载大文件非常有用,因为它不会一次性占用大量内存。
  • 示例:

    response = requests.get('https://example.com/large-file.zip', stream=True)
    # 分块写入文件,避免内存耗尽
    with open('large-file.zip', 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            if chunk:  # 过滤掉保持连接的新块
                f.write(chunk)

重定向 (allow_redirects)

  • 类型: bool
  • 描述: 控制是否允许服务器重定向。
    • True (默认): 允许 requests 自动处理重定向。
    • False: 禁止重定向,响应将是第一次收到的响应。
  • 示例:
    # 获取重定向前的最终 URL
    response = requests.get('http://github.com/', allow_redirects=False)
    print(response.status_code) # 301
    print(response.url)         # 'https://github.com/'

客户端证书 (cert)

  • 类型: strtuple

  • 描述: 用于指定客户端证书,进行双向 SSL 认证。

    • str: 单个文件路径(包含证书和私钥)。
    • tuple: (cert_file, key_file) 两个文件的路径。
  • 示例:

    # 单个文件包含证书和私钥
    response = requests.get('https://httpbin.org/get', cert='/path/client.cert')
    # 两个文件分别存放
    response = requests.get('https://httpbin.org/get', cert=('/path/client.cert', '/path/client.key'))

总结表格

参数 类型 描述 常见场景
url str 请求的目标地址 必须参数
params dict URL 查询参数 GET 请求,搜索
data dict 表单数据 POST 提交传统表单
json dict JSON 格式数据 POST/PUT 与 REST API 交互
headers dict 自定义请求头 设置 Content-Type, Authorization
cookies dict 发送 cookies 维护登录状态
auth tuple HTTP 身份验证 基本身份认证
files dict 文件上传 上传图片、文档等
timeout float/tuple 请求超时时间 必须设置,防止程序卡死
proxies dict 设置代理 翻墙、抓包
verify bool/str SSL 证书验证 连接 HTTPS 网站
stream bool 流式下载 下载大文件
allow_redirects bool 是否允许重定向 通常保持默认
cert str/tuple 客户端证书 双向 SSL 认证

掌握这些参数,你就可以灵活地使用 requests 库应对绝大多数 HTTP 请求场景了。

分享:
扫描分享到社交APP
上一篇
下一篇