1. import asyncio
    2. import aiohttp
    3. url = 'https://www.baidu.com/'
    4. async def test(url, semaphore):
    5. async with semaphore:
    6. async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
    7. async with session.get(url) as response:
    8. res = response.status
    9. ret = await response.read()
    10. print(res)
    11. if res != 200:
    12. raise
    13. return res
    14. async def create_tasks():
    15. semaphore = asyncio.Semaphore(500) # 限制并发量为500
    16. to_get = [test(url, semaphore) for _ in range(500)] # 总共1000任务
    17. await asyncio.wait(to_get)
    18. if __name__ == '__main__':
    19. loop = asyncio.get_event_loop()
    20. loop.run_until_complete(create_tasks())
    21. loop.close()