import asyncio import aiohttp import time def test(number): start = time.time() async def get(url): session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=64, verify_ssl=False)) response = await session.get(url) await response.text() await session.close() return response async def request(): url = 'https://static1.scrape.center/' await get(url) tasks = [asyncio.ensure_future(request()) for _ in range(number)] loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) end = time.time() print('Number:', number, 'Cost time:', end - start) for number in [1, 3, 5, 10]: test(number)
结果如下:
Number: 1 Cost time: 0.4136490821838379 Number: 3 Cost time: 0.17262792587280273 Number: 5 Cost time: 0.17714190483093262 Number: 10 Cost time: 0.16022205352783203
摘自拉勾教育《52讲轻松搞定网络爬虫》之异步爬虫的原理和解析