Requests - 代理
Requests:通过代理路由流量
Section titled “Requests:通过代理路由流量”代理服务器(proxy server)充当客户端从其他服务器请求资源时的中介。使用代理可能出于多种原因,例如访问受限网络内的资源、增强安全性、匿名性,或用于开发和测试目的。requests 库为通过代理路由 HTTP(S) 请求提供了直接支持。
代理的工作原理
Section titled “代理的工作原理”当您使用 requests 与代理一起工作时:
- 您的客户端(使用
requests的 Python 脚本)将请求发送到代理服务器。 - 代理服务器将您的请求转发给目标服务器(例如,
httpbin.org)。 - 目标服务器将响应发送回代理服务器。
- 代理服务器将此响应转发回您的客户端。
在 requests 中配置代理
Section titled “在 requests 中配置代理”您可以通过在请求方法(例如 requests.get()、requests.post())中向 proxies 参数传递一个字典来指定代理。该字典应将 URL 方案(如 ‘http’ 或 ‘https’)映射到代理服务器的 URL。
示例:基本的 HTTP 和 HTTPS 代理
Section titled “示例:基本的 HTTP 和 HTTPS 代理”要使用代理,您需要知道其地址和端口。在本例中,我们假设您有一个 HTTP 代理位于 http://myproxy.example.com:8080,以及一个 HTTPS 代理(它本身可能是一个能够隧道化 HTTPS 流量的 HTTP 代理)位于 http://secureproxy.example.com:8888。
import requests
# Replace with your actual proxy addresses and ports# If your HTTPS proxy is also an HTTP proxy, the scheme is 'http' for its address# 请替换为您的实际代理地址和端口# 如果您的 HTTPS 代理本身也是一个 HTTP 代理,则其地址的方案是 'http'proxies_config = { 'http': 'http://myproxy.example.com:8080', # For HTTP requests - 用于 HTTP 请求 'https': 'http://secureproxy.example.com:8888' # For HTTPS requests - 用于 HTTPS 请求}
# Test with an HTTP URL - 测试一个 HTTP URLtry: print("Attempting HTTP request via proxy...") # 尝试通过代理发送 HTTP 请求... response_http = requests.get('http://httpbin.org/ip', proxies=proxies_config) print(f"HTTP Request Status: {response_http.status_code}") # HTTP 请求状态码: print(f"Origin IP (should be proxy's IP): {response_http.json()['origin']}") # 原始 IP (应为代理的 IP):except requests.exceptions.ProxyError as e: print(f"HTTP Proxy Error: {e}. Ensure your proxy is running and accessible.") # HTTP 代理错误:{e}。请确保您的代理正在运行且可访问。except requests.exceptions.RequestException as e: print(f"HTTP Request Error: {e}") # HTTP 请求错误:{e}
print("\n---\n")
# Test with an HTTPS URL - 测试一个 HTTPS URLtry: print("Attempting HTTPS request via proxy...") # 尝试通过代理发送 HTTPS 请求... response_https = requests.get('https://httpbin.org/ip', proxies=proxies_config) print(f"HTTPS Request Status: {response_https.status_code}") # HTTPS 请求状态码: print(f"Origin IP (should be proxy's IP): {response_https.json()['origin']}") # 原始 IP (应为代理的 IP):except requests.exceptions.ProxyError as e: print(f"HTTPS Proxy Error: {e}. Ensure your proxy is running and accessible.") # HTTPS 代理错误:{e}。请确保您的代理正在运行且可访问。except requests.exceptions.RequestException as e: print(f"HTTPS Request Error: {e}") # HTTPS 请求错误:{e}**注意:**为了使这些示例正常工作,您必须在指定的地址和端口上运行实际的代理服务器,并且它们必须配置为允许您的机器进行连接。如果 myproxy.example.com 不是一个真实的代理,这些请求将会失败。
输出(如果代理工作正常且 httpbin.org/ip 可达)
Section titled “输出(如果代理工作正常且 httpbin.org/ip 可达)”Attempting HTTP request via proxy...HTTP Request Status: 200Origin IP (should be proxy's IP): <IP_ADDRESS_OF_HTTP_PROXY>
---
Attempting HTTPS request via proxy...HTTPS Request Status: 200Origin IP (should be proxy's IP): <IP_ADDRESS_OF_HTTPS_PROXY>httpbin.org/ip 端点返回接收到请求的 IP 地址。如果代理工作正常,此 IP 应该是您的代理服务器的 IP,而不是您本地机器的 IP。
需要身份验证的代理
Section titled “需要身份验证的代理”如果您的代理服务器需要用户名和密码,请将它们包含在代理 URL 中:
proxies_auth = { 'http': 'http://user:password@myproxy.example.com:8080', 'https': 'http://user:password@secureproxy.example.com:8888'}
# response = requests.get('http://httpbin.org/ip', proxies=proxies_auth)请记住,如果用户名或密码中包含特殊字符,必要时需要进行 URL 编码。
SOCKS 代理
Section titled “SOCKS 代理”requests 本身不直接支持 SOCKS 代理。但是,您可以通过安装额外的软件包(如 PySocks)来添加 SOCKS 代理支持:
pip install pysocks安装后,您可以使用 socks5://、socks5h://(用于远程 DNS 解析)、socks4:// 或 socks4a:// 方案来指定 SOCKS 代理:
proxies_socks = { 'http': 'socks5h://user:password@my-socks-proxy.example.com:1080', 'https': 'socks5h://user:password@my-socks-proxy.example.com:1080'}
# response = requests.get('https://httpbin.org/ip', proxies=proxies_socks)用于代理的环境变量
Section titled “用于代理的环境变量”如果在请求中未提供 proxies 参数,requests 将自动尝试使用标准环境变量中的代理设置。这些变量包括:
HTTP_PROXY:用于 HTTP 流量。HTTPS_PROXY:用于 HTTPS 流量。NO_PROXY:一个逗号分隔的主机名列表,这些主机名应绕过代理。
例如,在您的 shell 中:
# On Linux/macOS# 在 Linux/macOS 上export HTTP_PROXY="http://myproxy.example.com:8080"export HTTPS_PROXY="http://secureproxy.example.com:8888"
# On Windows (Command Prompt)# 在 Windows (命令提示符) 上set HTTP_PROXY=http://myproxy.example.com:8080set HTTPS_PROXY=http://secureproxy.example.com:8888如果设置了这些环境变量,requests 将默认使用它们,而无需在您的代码中包含 proxies 参数。这通常是系统范围或特定用户代理配置的首选方式。
常见问题和故障排除
Section titled “常见问题和故障排除”- 代理未运行/不可访问: 确保代理服务器正在运行且可从您的机器访问。网络防火墙可能会阻止连接。
- 身份验证错误: 如果您的代理需要身份验证,请仔细检查凭据。
- HTTPS 检查(中间人攻击): 企业代理有时会拦截和解密 HTTPS 流量。这可能需要安装您的系统或
requests信任的自定义根证书。有关更多详细信息,请参阅requests文档中关于 SSL 验证的部分(使用verify参数)。 - 错误的代理方案: 确保您为代理服务器类型和地址使用了正确的方案(例如,
http://、https://、socks5://)。
有效地使用代理使 requests 能够在各种网络环境和特殊任务中运行。请始终确保您的代理使用符合相关服务条款和道德准则。