asyncio相关 - 一个简单的示例

  • 作者:KK

  • 发表日期:2020.02.14


下面的代码示例了如何基于 aiohttp 网络库将2个网址的HTML同时请求下来:

import asyncio, aiohttp

async def getHtml(url):
	async with aiohttp.ClientSession() as httpSession:
		async with httpSession.get(url) as response:
			return await response.text()

async def main():
	tasks = []
	for url in ['http://www.kkh86.com/it', 'http://www.kkh86.com/it/python']:
		tasks.append(getHtml(url)) #这时候还没执行请求的,只是返回了一个生成器

	result = await asyncio.gather(*tasks) #开始执行,注意这里是  *tasks ,前面带个 * 号把参数展开
	print(
		'请求1的HTML',
		result[0][:100],
		'\n\n\n========================== 分割线 ==========================\n\n\n',
		'请求2的HTML',
		result[1][:100]
	)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()