自从Python 3.5引入async with
之后,docs中推荐的aiohttp
语法已经改变.现在,要获得他们建议的单一url:
import aiohttp
import asyncio
async def fetch(session, url):
with aiohttp.Timeout(10):
async with session.get(url) as response:
return await response.text()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
with aiohttp.ClientSession(loop=loop) as session:
html = loop.run_until_complete(
fetch(session, 'http://python.org'))
print(html)
我如何修改它来获取一个url集合,而不是一个url?
在旧的asyncio
个示例中,您将设置一个任务列表,例如
tasks = [
fetch(session, 'http://cnn.com'),
fetch(session, 'http://google.com'),
fetch(session, 'http://twitter.com')
]
我试图将这样的列表与上述方法结合起来,但失败了.