Python-requests

requests 库简介

requests 库是 Python 中用于发送 HTTP 请求的常用库,以下通过实例简单介绍一下用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import requests

# 目标 URL
url = 'https://www.example.com'

# 发送 GET 请求
response = requests.get(url)

# 检查响应状态码
if response.status_code == 200:
# 打印响应内容
print('响应内容:')
print(response.text)
else:
print(f'请求失败,状态码:{response.status_code}')

requests 库中基于 HTTP 请求方法内置了大量方法,如:

  • requests.get(url, params=None, **kwargs):发送 HTTP GET 请求以从服务器获取资源。
  • requests.post(url, data=None, json=None, **kwargs):发送 HTTP POST 请求,通常用于向服务器提交数据。
  • requests.put(url, data=None, **kwargs):发送 HTTP PUT 请求,常用于更新服务器上的资源。
  • requests.delete(url, **kwargs):发送 HTTP DELETE 请求,用于请求服务器删除指定的资源。
  • requests.head(url, **kwargs):发送 HTTP HEAD 请求,只返回响应头,不返回响应体。
  • requests.options(url, **kwargs):发送 HTTP OPTIONS 请求,用于获取服务器支持的请求方法等信息。
  • requests.request(method, url, **kwargs):通用的请求方法,可根据 method 参数指定的 HTTP 请求方法发送请求。

更多方法不再赘述,下面对各方法的参数进行说明:

requests 库各方法的参数与用法

通用参数(适用于所有HTTP方法)

所有请求方法(如 get(), post(), put() 等)都支持以下参数:

  1. url (必填)
  • 类型: 字符串

  • 作用: 请求的目标URL。

  • 示例:

    1
    response = requests.get(url="https://api.example.com/data")
  1. params (可选)
  • 类型: 字典、元组列表或字节

  • 作用: 将参数拼接到URL中,形成查询字符串(query string)。

  • 示例:

    1
    2
    3
    params = {'key1': 'value1', 'key2': 'value2'}
    response = requests.get(url, params=params)
    # 实际请求URL变为:https://api.example.com/data?key1=value1&key2=value2
  1. headers (可选)
  • 类型: 字典

  • 作用: 设置HTTP请求头信息(如User-Agent、Content-Type等)。

  • 示例:

    1
    2
    headers = {'User-Agent': 'my-app/1.0', 'Content-Type': 'application/json'}
    response = requests.get(url, headers=headers)
  1. timeout (可选)
  • 类型: 浮点数或元组

  • 作用: 设置请求超时时间(秒)。若服务器在指定时间内未响应,抛出 Timeout 异常。

  • 示例:

    1
    2
    response = requests.get(url, timeout=5)          # 连接+读取总超时5秒
    response = requests.get(url, timeout=(3, 10)) # 连接3秒,读取10秒
  1. auth (可选)
  • 类型: 元组或自定义认证类

  • 作用: 用于HTTP基本认证(如用户名密码)。

  • 示例:

    1
    2
    auth = ('username', 'password')
    response = requests.get(url, auth=auth)
  1. cookies (可选)
  • 类型: 字典或CookieJar对象

  • 作用: 发送Cookie到服务器。

  • 示例:

    1
    2
    cookies = {'session_id': '12345abc'}
    response = requests.get(url, cookies=cookies)
  1. allow_redirects (可选)
  • 类型: 布尔值

  • 作用: 是否允许重定向(默认True)。

  • 示例:

    1
    response = requests.get(url, allow_redirects=False)
  1. verify (可选)
  • 类型: 布尔值或字符串(证书路径)

  • 作用: 是否验证SSL证书(默认True)。设为False可跳过验证(不推荐生产环境使用)。

  • 示例:

    1
    response = requests.get(url, verify=False)  # 关闭SSL验证
  1. proxies (可选)
  • 类型: 字典

  • 作用: 设置代理服务器。

  • 示例:

    1
    2
    proxies = {'http': 'http://10.10.1.10:3128', 'https': 'http://10.10.1.10:1080'}
    response = requests.get(url, proxies=proxies)
  1. stream (可选)
  • 类型: 布尔值

  • 作用: 是否以流模式下载(适合大文件,避免立即加载到内存)。

  • 示例:

    1
    2
    3
    4
    5
    response = requests.get(url, stream=True)
    if response.status_code == 200:
    with open('large_file.zip', 'wb') as f:
    for chunk in response.iter_content(1024):
    f.write(chunk)

针对不同HTTP方法的参数

  1. GET请求:requests.get()
  • 主要用于获取数据,参数通过 params 传递。

  • 示例:

    1
    2
    3
    4
    response = requests.get(
    url="https://example.com/search",
    params={'query': 'python', 'page': 2},
    )
  1. POST请求:requests.post()
  • 用于提交数据,常用参数:**data**, json, **files**。

  • data 参数:

    • 类型: 字典、元组列表、字符串、字节流
    • 作用: 发送表单数据(application/x-www-form-urlencoded ,默认的表单编码格式,适用于提交简单的文本数据)。
    • 示例:
    1
    2
    3
    4
    5
     data = {'username': 'admin', 'password': 'secret'} # 字典类型
    response = requests.post(url, data=data)

    data = [('fruit', 'apple'), ('fruit', 'banana'), ('vegetable', 'carrot')] # 元组列表类型,适用于需要处理多个同名字段或对数据顺序有要求的情况。传参到服务端会把同名参数的值以类似 "fruit":["apple","banana"] 这样的形式存放。
    data = 'name=Bob&age=30' # 用于传输 URL 编码后的字符串
  • json 参数:

    • 类型: 字典
    • 作用: 发送JSON数据(自动设置Content-Type: application/json)。
    • 示例:
    1
    2
    json_data = {'name': 'John', 'age': 30}
    response = requests.post(url, json=json_data)
  • files 参数:

    • 类型: 字典
    • 作用: 上传文件(multipart/form-data ,用于上传文件或包含二进制数据的表单)。
    • 示例:
    1
    2
    files = {'file': open('report.pdf', 'rb')}
    response = requests.post(url, files=files)
  1. PUT请求:requests.put()
  • 用于更新资源,参数与 post() 相同(data, json, files)。

  • 示例:

    1
    response = requests.put(url, json={'title': 'New Title'})
  1. DELETE请求:requests.delete()
  • 用于删除资源,通常不需要请求体。

  • 示例:

    1
    response = requests.delete(url)
  1. 其他方法:head(), options(), patch()
  • 参数与 get()post() 类似,但使用频率较低。

高级参数:requests.request()

  • 作用: 通用请求方法,可通过 method 参数指定HTTP方法(如GETPOST)。

  • 示例:

    1
    response = requests.request(method='POST', url=url, json=data)

关于 requests 库返回的对象

在 Python 的 requests 库中,如 response = requests.get(url=url) 返回的是一个 对象(属于 requests.models.Response 类)。这个对象包含了 HTTP 请求的所有响应信息,但直接打印 response 并不会显示所有内容,而是会返回一个对象的内存地址表示(例如:<Response [200]>)。

以下是对 response 对象常用属性与方法的介绍:

常用属性

  1. status_code
    • HTTP 响应的状态码(如 200 表示成功,404 表示未找到)。
    • 示例:response.status_code
  2. text
    • 响应内容的字符串形式(自动根据响应编码解码)。
    • 示例:response.text
  3. content
    • 响应内容的二进制形式(原始字节流)。
    • 示例:response.content
  4. headers
    • 以字典形式返回响应头(键不区分大小写)。
    • 示例:response.headers['Content-Type']
  5. url
    • 最终请求的 URL(处理重定向后)。
    • 示例:response.url
  6. encoding
    • 响应的编码格式(可手动修改以修正解码问题)。
    • 示例:response.encoding = 'utf-8'
  7. cookies
    • 服务器返回的 Cookies(RequestsCookieJar 对象)。
    • 示例:response.cookies.get('session_id')
      (此处 get() 并非requests.get(),用于从 cookies 中获取指定名称的 cookie 值)
  8. history
    • 重定向历史记录(列表形式,按请求顺序排列)。
    • 示例:response.history[0].status_code

常用方法

  1. json()
    • 将 JSON 响应内容解析为 Python 字典/列表。
    • 示例:data = response.json()
  2. raise_for_status()
    • 若状态码为 4xx/5xx,抛出异常(用于错误处理)。
    • 示例:response.raise_for_status()

其他属性

  1. request
    • 返回对应的请求对象(包含请求方法、URL、头信息等)。
    • 示例:response.request.method
  2. elapsed
    • 请求耗时(datetime.timedelta 对象)。
    • 示例:response.elapsed.total_seconds()
  3. reason
    • 状态码的文本描述(如 200reasonOK)。
    • 示例:response.reason
  4. is_redirect
    • 布尔值,表示是否重定向。
    • 示例:if response.is_redirect: ...
  5. apparent_encoding
    • 通过内容推断的编码格式(比 encoding 更可靠)。
    • 示例:response.encoding = response.apparent_encoding
  6. raw
    • 原始响应流(需在请求中设置 stream=True)。
    • 示例:response.raw.read(10)

其他知识点

requests.Session()

Python 的 requests.Session()客户端的工具(注意与服务端的 Session 区分),目的是简化客户端与服务端交互时的状态管理。它的核心作用是:

**自动管理 Cookies **

  • 自动保存服务端通过 Set-Cookie 返回的所有 Cookies(包括 session_id 等)
  • 自动携带这些 Cookies 发送后续请求

示例:

1
2
3
4
5
6
7
8
9
10
import requests

# 创建客户端会话(自动管理 Cookies)
session = requests.Session()

# 1.服务端返回 Cookie 并自动保存到 Session 中
session.post("https://example.com/login", data={"user": "test", "pass": "123"})

# 2.通过 session.get() 这样的形式,自动携带 Cookie(无需手动处理 Cookie 并添加到 header 中)
response = session.get("https://example.com/profile")

其他功能

  • 连接池(Connection Pooling):复用 TCP 连接,提升性能
  • 统一配置:预先设置 Headers、Auth、Proxies 等,适用于所有请求