Python异步编程: 揭秘异步编程的本质, 优化代码性能
2024-05-16

import asyncio

async def get_html(url):
async with aioHttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()

async def main():
# 并发地获取多个网页的HTML内容
urls = ["https://www.example.com", "https://www.example2.com", "https://www.example3.com"]
tasks = [get_html(url) for url in urls]
html_content = await asyncio.gather(*tasks)

# 处理获取到的HTML内容
for content in html_content:
print(content)

if __name__ == "__main__":
asyncio.run(main())
登录后复制