import asyncio
import aiohttp
url = 'https://www.baidu.com/'
async def test(url, semaphore):
async with semaphore:
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
async with session.get(url) as response:
res = response.status
ret = await response.read()
print(res)
if res != 200:
raise
return res
async def create_tasks():
semaphore = asyncio.Semaphore(500) # 限制并发量为500
to_get = [test(url, semaphore) for _ in range(500)] # 总共1000任务
await asyncio.wait(to_get)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(create_tasks())
loop.close()