2025-03-05
编程
00
请注意,本文编写于 54 天前,最后修改于 54 天前,其中某些信息可能已经过时。

目录

1. 安装
2. 发送网络请求
2.1 发送 GET 请求
添加查询参数
2.2 发送 POST 请求
3. 详细操作
3.1使用代理
使用 HTTP 代理
使用带认证的代理
使用环境变量设置代理
忽略 SSL 验证(不推荐用于生产环境)
3.2使用 Headers 和 Params
3.2使用 data(post)
3.4 使用 Session 对象
3.5 处理 JSON 响应
3.6 错误和异常处理
3.7 文件上传
3.8 流式请求
3.9 处理超时

requests 是一个非常流行的 Python HTTP 库,它使得发送 HTTP/1.1 请求变得非常简单。无论你需要执行 GET、POST、PUT 或 DELETE 等操作,requests 都能以一种直观且易于使用的方式帮助你完成任务。它支持复杂的用例,如通过 multipart 文件上传、流式传输大型下载、会话保持(cookies)、HTTP(S) 代理支持等。

1. 安装

首先,你需要安装 requests 包。可以通过 pip 来安装:

bash
pip install requests

2. 发送网络请求

2.1 发送 GET 请求

这是最基本的用法,用于从指定 URL 获取数据。

python
import requests response = requests.get('https://api.github.com') # 输出状态码 print(response.status_code) # 输出响应内容 print(response.text)
添加查询参数

在 GET 请求中,经常需要添加查询参数:

python
import requests # URL 和查询参数 url = 'https://httpbin.org/get' params = {'key1': 'value1', 'key2': 'value2'} # 发送 GET 请求并附带查询参数 response = requests.get(url, params=params) # 输出完整的请求 URL print(f"完整URL: {response.url}") # 输出响应内容 print(f"响应内容: {response.text}")

2.2 发送 POST 请求

当你需要向服务器提交数据时,可以使用 POST 方法。

python
import requests url = 'https://httpbin.org/post' data = {'key': 'value'} response = requests.post(url, data=data) # 输出响应内容 print(response.text)

3. 详细操作

3.1使用代理

使用 requests 库通过代理发送 HTTP 请求非常简单。你可以通过设置 proxies 参数来指定代理服务器。

使用 HTTP 代理

假设你有一个 HTTP 代理服务器,地址为 http://10.10.1.10:3128,你可以这样设置:

python
import requests # 定义代理 proxies = { 'http': 'http://10.10.1.10:3128', 'https': 'http://10.10.1.10:3128', } # 发送 GET 请求并使用代理 response = requests.get('http://httpbin.org/ip', proxies=proxies) # 输出响应内容 print(f"您的 IP 地址是: {response.text}")
使用带认证的代理

如果你的代理服务器需要用户名和密码进行认证,可以在代理 URL 中包含这些信息:

python
import requests # 定义带认证的代理 proxies = { 'http': 'http://user:password@10.10.1.10:3128', 'https': 'http://user:password@10.10.1.10:3128', } # 发送 GET 请求并使用带认证的代理 response = requests.get('http://httpbin.org/ip', proxies=proxies) # 输出响应内容 print(f"您的 IP 地址是: {response.text}")
使用环境变量设置代理

你还可以通过环境变量来设置代理,requests 会自动读取这些环境变量:

bash
export HTTP_PROXY="http://10.10.1.10:3128" export HTTPS_PROXY="http://10.10.1.10:3128"

在 Python 脚本中无需显式传递 proxies 参数:

python
import requests # 环境变量已设置,直接发送请求 response = requests.get('http://httpbin.org/ip') # 输出响应内容 print(f"您的 IP 地址是: {response.text}")
忽略 SSL 验证(不推荐用于生产环境)

有时你可能需要忽略 SSL 验证(例如,当使用自签名证书时)。可以通过设置 verify 参数为 False 来实现:

python
import requests # 定义代理 proxies = { 'http': 'http://10.10.1.10:3128', 'https': 'http://10.10.1.10:3128', } # 发送 GET 请求并使用代理,忽略 SSL 验证 response = requests.get('https://httpbin.org/ip', proxies=proxies, verify=False) # 输出响应内容 print(f"您的 IP 地址是: {response.text}")

注意:忽略 SSL 验证可能会导致安全风险,请仅在测试环境中使用此选项。

3.2使用 Headers 和 Params

有时,你可能需要添加自定义的 headers 或者 URL 参数。

python
import requests url = 'https://httpbin.org/get' headers = {'user-agent': 'my-app/0.0.1'} params = {'key1': 'value1', 'key2': 'value2'} response = requests.get(url, headers=headers, params=params) # 输出响应内容 print(response.text)

3.2使用 data(post)

get请求不能携带参数

python
import requests url = 'https://httpbin.org/get' headers = {'user-agent': 'my-app/0.0.1'} data = {'key1': 'value1', 'key2': 'value2'} response = requests.get(url, headers=headers, data=data) # 输出响应内容 print(response.text)

3.4 使用 Session 对象

对于需要保持会话状态的操作(如登录后访问页面),可以使用 Session 对象:

python
import requests # 创建一个会话对象 session = requests.Session() # 登录请求 login_url = 'https://httpbin.org/basic-auth/user/passwd' auth = ('user', 'passwd') session.auth = auth # 发送登录请求 response = session.get(login_url) # 输出响应内容 print(f"登录响应: {response.text}") # 访问需要登录的页面 protected_url = 'https://httpbin.org/basic-auth/user/passwd' response = session.get(protected_url) # 输出响应内容 print(f"受保护页面响应: {response.text}") # 关闭会话 session.close()

3.5 处理 JSON 响应

许多现代 API 返回 JSON 格式的响应,requests 提供了方便的方法来处理这些响应。

python
import requests response = requests.get('https://api.github.com') # 将响应内容解析为 JSON json_response = response.json() # 输出 JSON 内容 print(json_response)

3.6 错误和异常处理

在进行网络请求时,错误是不可避免的。requests 提供了异常处理机制来捕获这些错误。

python
import requests from requests.exceptions import HTTPError try: response = requests.get('https://api.github.com') # 如果响应状态码不是成功的代码,则引发 HTTPError 异常 response.raise_for_status() except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except Exception as err: print(f'Other error occurred: {err}') else: print('Success!')

3.7 文件上传

你可以轻松地使用 requests 上传文件:

python
import requests # URL 和文件路径 url = 'https://httpbin.org/post' files = {'file': open('example.txt', 'rb')} # 发送 POST 请求并上传文件 response = requests.post(url, files=files) # 输出响应内容 print(f"响应内容: {response.text}")

注意:确保你有一个名为 example.txt 的文件存在于当前工作目录中。

3.8 流式请求

当你需要处理大文件下载时,可以使用流式请求:

python
import requests url = 'https://speed.hetzner.de/100MB.bin' with requests.get(url, stream=True) as r: r.raise_for_status() with open('large_file.bin', 'wb') as f: for chunk in r.iter_content(chunk_size=8192): if chunk: # 过滤掉 keep-alive 新块 f.write(chunk)

3.9 处理超时

为了防止请求长时间挂起,可以设置超时参数:

python
import requests # 定义代理 try: # 发送 GET 请求并使用代理,设置超时时间为5秒 response = requests.get('http://httpbin.org/ip', timeout=5) # 输出响应内容 print(f"您的 IP 地址是: {response.text}") except requests.Timeout as e: print(f"请求超时: {e}") except requests.RequestException as e: print(f"请求错误: {e}")