Python异步爬虫用代理IP:aiohttp 与并发控制-易代理
同步爬虫够用就别上异步。但日采十万页以上,aiohttp 是标配。异步场景里代理IP 的坑不在“怎么挂”,在连接爆炸和出口混用。
一、aiohttp 基础挂代理
pythonimport aiohttp, asyncioasync def fetch(session, url, proxy): async with session.get(url, proxy=proxy, timeout=15) as r: return await r.text()async def main(): proxy = "http://user:pass@gate:port" async with aiohttp.ClientSession() as session: html = await fetch(session, "https://httpbin.org/ip", proxy) print(html) asyncio.run(main())
SOCKS5 要装 aiohttp-socks,用 ProxyConnector。
二、连接池与并发信号量
异步不是无限开协程:
pythonconnector = aiohttp.TCPConnector(limit=50, limit_per_host=5) sem = asyncio.Semaphore(20)async def fetch(session, url, proxy): async with sem: async with session.get(url, proxy=proxy) as r: return await r.text()
并发数从 20~50 起步,看成功率和耗时再调。并发过高,超时和换 IP 成本反而拖垮吞吐。
三、每个任务绑定固定出口
会话保持场景(登录态、地区回归)要用粘性出口:
python# 同一 task 复用同一 proxy 字符串
别在协程里全局随机取,否则 Cookie 和地区全乱。
四、异常分级与退避
pythontry: return await fetch(...)except (ProxyConnectionError, TimeoutError): await asyncio.sleep(2 ** attempt) proxy = pick_new_proxy()
失败换 IP + 指数退避,别连击。死信任务进队列,结束统一补采。
五、指标埋点
异步里更要埋:
CONNECT 成功数
TLS 握手耗时
隧道断连数
每代理成功/失败
每目标站验证码率
代理IP 在异步爬虫里,是“可观测资源”,不是黑盒字符串。