Python 爬虫代理 IP 配合 aiohttp 做异步采集-易代理
同步爬虫撑不住高频任务
Requests 是同步的,一个请求没回来,线程就干等。任务到了几千几万个页面,这种等法太浪费。IO 密集型采集里,aiohttp 更合适。单进程也能同时挂大量请求,延迟藏在网络等待里。
但异步不是“并发调大就完事”。出口层更要稳。Python 爬虫代理 IP 在 aiohttp 里如果用得糙,错误会成倍放大:一个坏网关,几百个协程一起超时。
aiohttp 基础代理写法
pythonimport aiohttpimport asyncioasync def fetch(session, url, proxy): try: async with session.get(url, proxy=proxy, timeout=aiohttp.ClientTimeout(total=10)) as resp: text = await resp.text() return resp.status, text[:100] except Exception as e: return None, str(e)async def main(): proxy = "http://用户名:密码@网关地址:端口" urls = ["https://httpbin.org/ip" for _ in range(20)] async with aiohttp.ClientSession() as session: tasks = [fetch(session, u, proxy) for u in urls] for status, body in await asyncio.gather(*tasks): print(status, body) asyncio.run(main())
动态转发网关下,不需要自己维护 IP 列表,aiohttp 每次连网关,由服务端换出口。Python 爬虫代理 IP 的“动态”和 aiohttp 的“异步”是两套能力,别混为一谈。
连接器并发要设上限
aiohttp 默认连接数不无限放。生产里要显式限制,不然代理网关被你打挂。
pythonconnector = aiohttp.TCPConnector(limit=50, limit_per_host=10, ttl_dns_cache=300) timeout = aiohttp.ClientTimeout(total=15, connect=8, sock_read=10)
Python 爬虫代理 IP 再好,也经不住单客户端无脑并发。limit 是护栏,不是性能开关。
失败请求要做退避
异步里重试不能用 time.sleep,要用 asyncio.sleep。
pythonasync def fetch_with_retry(session, url, proxy, max_retries=3): for attempt in range(1, max_retries + 1): try: async with session.get(url, proxy=proxy, timeout=aiohttp.ClientTimeout(total=10)) as resp: if resp.status == 200: return await resp.text() except Exception as e: print(f"第{attempt}次异常:{e}") await asyncio.sleep(2 ** attempt) return None指数退避比固定重试更稳。Python 爬虫代理 IP 遇到瞬时抖动,退一下再发,比马上重锤温柔得多。
信号量控制真实并发
就算 connector 有限制,业务层也该用 Semaphore 控节奏:
pythonsem = asyncio.Semaphore(20)async def bounded_fetch(sem, session, url, proxy): async with sem: return await fetch_with_retry(session, url, proxy)
这样你心里有数:同时真跑的只有 20 个。Python 爬虫代理 IP 的账单、网关负载、目标站限流,全都更好算。
响应内容别全量堆内存
异步跑得快,很多人把 resp.text() 全读进来再解析,内存一下炸了。大页面可以用流式读,或者只取前段做命中判断。
pythonasync with session.get(url, proxy=proxy) as resp: chunk = await resp.content.read(4096)
Python 爬虫代理 IP 解决出口,内存管理解决存活。两套都不管,爬虫跑两小时就被 OOM 干掉。
小结
aiohttp 配 Python 爬虫代理 IP,适合高频、公开、可重试的采集任务。别把异步当成“可以莽”,真正稳的异步爬虫,代理、超时、信号量、退避、解析层全都有边界。
相关标签:代理ip,ip代理,http代理,代理服务器ip,开放代理,文档中心,新闻,动态住宅ip,ip池,socks5代理