基础:proxies 字典
requests 根据所请求 URL 的协议选择代理。请同时设置 http 和 https 两个键(通常指向同一代理),否则 HTTPS 请求会绕过代理。代理 URL 本身包含协议、凭据、主机和端口。
import requests
PROXY = "http://USERNAME:PASSWORD@PROXY_HOST:PORT"
proxies = {"http": PROXY, "https": PROXY}
r = requests.get("https://api.ipify.org", proxies=proxies, timeout=15)
print(r.text) # the proxy's IP使用远程 DNS 的 SOCKS5
安装 SOCKS 扩展包,然后使用 socks5h 协议。h 表示主机名由代理解析。使用普通的 socks5 时,你的机器会先解析域名:DNS 从你自己的网络发出,区域性网站可能返回错误国家的结果。
| 协议 | 与代理之间的协议 | DNS 解析方 |
|---|---|---|
| http:// | HTTP(HTTPS 网站使用 CONNECT) | 代理 |
| socks5:// | SOCKS5 | 你的机器 |
| socks5h:// | SOCKS5 | 代理(推荐) |
# pip install "requests[socks]"
import requests
PROXY = "socks5h://USERNAME:PASSWORD@PROXY_HOST:PORT"
r = requests.get("https://api.ipify.org",
proxies={"http": PROXY, "https": PROXY}, timeout=15)
print(r.text)Session、超时与重试
复用 Session 以便连接池化,始终传入超时以防卡住的请求挂起程序,并且只做少量带退避的重试。urllib3 的 Retry 会为你处理退避。
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
PROXY = "socks5h://USERNAME:PASSWORD@PROXY_HOST:PORT"
session = requests.Session()
session.proxies = {"http": PROXY, "https": PROXY}
retry = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
session.mount("http://", HTTPAdapter(max_retries=retry))
session.mount("https://", HTTPAdapter(max_retries=retry))
r = session.get("https://example.com/", timeout=(10, 30)) # connect, readexport HTTPS_PROXY="http://USERNAME:PASSWORD@PROXY_HOST:PORT"
export HTTP_PROXY="$HTTPS_PROXY"
python my_script.py # requests reads these automatically常见错误
requests 中的大多数代理问题都来自少数几种错误,请先排查这些。
- 只设置了 http 键,导致 HTTPS 请求直连。
- 用了 socks5 而不是 socks5h,导致 DNS 在本地解析。
- 密码中的特殊字符没有进行 URL 编码(使用 urllib.parse.quote)。
- 没有设置超时,一个卡住的连接就会阻塞整个任务。
- 无限重试,在网站拒绝请求时成倍放大流量。
异步请求:httpx 和 aiohttp
需要同时发大量请求时,异步客户端比在 requests 外面套线程更高效。httpx 在客户端上设置代理,安装 socks 扩展后支持 SOCKS5。aiohttp 按请求传入 HTTP 代理,SOCKS5 需要 aiohttp-socks;rdns=True 表示通过代理解析主机名。
# pip install "httpx[socks]"
import asyncio, httpx
PROXY = "socks5://USERNAME:PASSWORD@PROXY_HOST:PORT"
async def main():
async with httpx.AsyncClient(proxy=PROXY, timeout=30) as client:
r = await client.get("https://api.ipify.org")
print(r.text)
asyncio.run(main())# pip install aiohttp aiohttp-socks
import asyncio, aiohttp
from aiohttp_socks import ProxyConnector
async def main():
# HTTP proxy: pass it per request
async with aiohttp.ClientSession() as s:
async with s.get("https://api.ipify.org", proxy="http://USERNAME:PASSWORD@PROXY_HOST:PORT") as r:
print(await r.text())
# SOCKS5: needs a connector
conn = ProxyConnector.from_url("socks5://USERNAME:PASSWORD@PROXY_HOST:PORT", rdns=True)
async with aiohttp.ClientSession(connector=conn) as s:
async with s.get("https://api.ipify.org") as r:
print(await r.text())
asyncio.run(main())轮换代理与错误处理
把请求分散到多个代理上,失败时换一个代理重试。把代理错误和目标网站的错误分开处理:ProxyError 表示代理没有连通,而网站返回 403 或 429 表示请求已经到达、被网站拒绝。
| 错误 | 原因 | 解决方法 |
|---|---|---|
| ProxyError | 无法连接代理或无法通过代理连接 | 检查主机、端口以及代理是否有效;换一个代理重试 |
| 407 Proxy Authentication Required | 代理登录信息错误或缺失 | 检查凭据;对密码中的特殊字符进行 URL 编码 |
| ConnectTimeout / ReadTimeout | 出口或目标网站较慢 | 提高超时时间或换代理重试 |
| 通过代理时出现 SSLError | TLS 被拦截或证书库过旧 | 更新 certifi;生产环境不要关闭证书验证 |
| 网站返回 403 或 429 | 网站拒绝或限流 | 降低频率、轮换 IP、发送合理的请求头 |
import random, requests
from urllib.parse import quote
PROXIES = [
"http://USERNAME:PASSWORD@PROXY_HOST_1:PORT",
"http://USERNAME:PASSWORD@PROXY_HOST_2:PORT",
]
def get(url):
for attempt in range(3):
proxy = random.choice(PROXIES)
try:
return requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=20)
except requests.exceptions.ProxyError:
continue # try another proxy
raise RuntimeError("all proxies failed")
# A password with @, : or / must be URL-encoded first:
password = quote("p@ss:word", safe="")代理认证、Session 代理以及绕过代理
requests 从代理 URL 中读取登录信息:http://USERNAME:PASSWORD@PROXY_HOST:PORT,对 HTTP 和 HTTPS 网站都有效。requests.auth.HTTPProxyAuth 只会给普通 HTTP 请求加上 Proxy-Authorization 头,对 HTTPS 没用,因为登录信息必须随 CONNECT 请求发出。凭据请放在由环境变量拼出的 URL 里,不要直接写进要提交的代码。
设置在 session.proxies 上的代理可能被环境里的 HTTP_PROXY 和 HTTPS_PROXY 覆盖,因为 requests 会把环境设置合并进每个请求。如果脚本忽略了你在 Session 上设置的代理,请设置 session.trust_env = False,或在每个请求中传入 proxies=。
想让某些主机不走代理,把它们写进 NO_PROXY。想让整个 Session 不走代理,使用 trust_env = False 且不设置 proxies。
import os, requests
from urllib.parse import quote
user = os.environ["PROXY_USER"]
password = quote(os.environ["PROXY_PASS"], safe="")
PROXY = f"http://{user}:{password}@PROXY_HOST:PORT"
session = requests.Session()
session.trust_env = False # ignore HTTP(S)_PROXY from the environment
session.proxies = {"http": PROXY, "https": PROXY}
print(session.get("https://api.ipify.org", timeout=15).text) # proxy IP
# No proxy at all for this session:
direct = requests.Session()
direct.trust_env = False
print(direct.get("https://api.ipify.org", timeout=15).text) # your own IPexport HTTPS_PROXY="http://USERNAME:PASSWORD@PROXY_HOST:PORT"
export NO_PROXY="localhost,127.0.0.1,.internal.example.com"
python my_script.py # these hosts skip the proxy