串行抓数据的痛点是等。每个请求 1 秒,十个就是 10 秒。
改成并发,同样的活一秒多就能干完。但并发不等于无脑开,限流必须一起做。
依赖与基础结构
# pip install httpx import asyncio, httpx
核心:用 gather 并发,用 semaphore 限流
SEM = asyncio.Semaphore(5)
async def fetch(client, url):
async with SEM:
try:
r = await client.get(url, timeout=10)
return url, r.status_code, len(r.text)
except Exception as e:
return url, None, str(e)
async def main(urls):
async with httpx.AsyncClient(headers={"User-Agent": "demo"}) as c:
results = await asyncio.gather(*(fetch(c, u) for u in urls))
for r in results:
print(r)三个必须注意的点
一是超时一定要设。不设超时,一个卡住的请求会拖住整批。
二是异常要在任务里捕获。gather 默认一个任务抛错就可能中断整体结果。
三是并发数别贪。5 到 10 是多数站点能接受的区间,具体看对方 robots 和限速。
用 asyncio.run 启动
asyncio.run(main(urls))
再往前一步
如果要做大批量任务,把 gather 换成 task group 加队列,就能做进度控制与重试。
但先把上面这个跑稳,再谈优化。