实现思路
- 导入必要的库:导入
asyncio
用于异步操作,aiohttp
用于进行异步HTTP请求。
- 定义一个函数:该函数负责发起单个HTTP请求并处理响应。
- 创建任务列表:将多个请求任务添加到任务列表中。
- 运行事件循环:使用
asyncio
的事件循环来并发执行这些任务。
核心代码
import asyncio
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
'http://example.com',
'http://example.org',
'http://example.net'
]
async with aiohttp.ClientSession() as session:
tasks = [fetch(session, url) for url in urls]
results = await asyncio.gather(*tasks)
for result in results:
print(result)
if __name__ == "__main__":
asyncio.run(main())