使用协程库httpx并发请求

httpx和aiohttp都是比较常用的异步请求库,当然requests+多线程或requests+gevent也是不错的选择。

一个使用httpx进行并发请求的脚本如下:

python 复制代码
import functools
import sys
import time

import anyio
import httpx


async def fetch(client, results, index) -> int:
    url = "https://qq.com"
    results[index] = r = await client.get(url)
    return len(r.content)


def timeit(func):
    @functools.wraps(func)
    async def deco(*args, **kw):
        start = time.time()
        rv = await func(*args, **kw)
        print(f"{func.__name__} Cost: {round(time.time()-start,1)} seconds.")
        return rv

    return deco


@timeit
async def main():
    if not sys.argv[1:]:
        print(f'Usage::\n  python {sys.argv[0]} 100\n')
        return
    total = int(sys.argv[1])
    results = [None] * total
    async with httpx.AsyncClient(follow_redirects=True, timeout=60) as client:
        async with anyio.create_task_group() as tg:
            for i in range(total):
                tg.start_soon(fetch, client, results, i)
    success = sum(map(bool, results))
    print(f"{total = }; Success: {success}; Failed: {total-success}")


if __name__ == "__main__":
    anyio.run(main)
相关推荐
小军要奋进11 天前
httpx模块的使用
笔记·爬虫·python·学习·httpx
Maybe_952725 天前
httpx.AsyncClient()的stream方法设置timeout超时
python·httpx·流式接口超时
数据知道2 个月前
python中httpx库的详细使用及案例
开发语言·爬虫·python·httpx
Maybe_95272 个月前
python使用httpx_sse调用sse流式接口对响应格式为application/json的错误信息的处理
python·sse·httpx
qq_527887872 个月前
【已解决】TypeError: AsyncConnectionPool.__init__(), new install bug, httpx==0.24.1
bug·httpx
CodeZ-Hao3 个月前
httpx上传文件/IO流缓慢的问题分析及解决
python·压力测试·httpx
waketzheng3 个月前
httpx.AsyncClient报错ProxyError: 504 Gateway Time-out
gateway·httpx
SunnyRivers4 个月前
基础库httpx的使用
爬虫·httpx
xybm16055 个月前
Dowex 50WX8 ion-exchange resin可以用于去除水中的金属离子(如钠、钾、镁、钙等)和其他杂质,提高水质,11119-67-8
python·flask·httpx·tornado
Learner_HJ6 个月前
猿人学 — 第1届第17题(解题思路附源码)
python·网络爬虫·httpx·猿人学