【发布时间】:2018-11-16 21:44:05
【问题描述】:
我正在尝试在 python 中使用异步从网站获取数据。作为示例,我使用了这段代码(在 A Better Coroutine Example 下):https://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/
现在这工作正常,但它将二进制块写入文件,我不希望它在文件中。我想要直接得到的数据。但我目前有一个协程对象列表,我无法从中获取数据。
代码:
# -*- coding: utf-8 -*-
import aiohttp
import asyncio
import async_timeout
async def fetch(session, url):
with async_timeout.timeout(10):
async with session.get(url) as response:
return await response.text()
async def main(loop, urls):
async with aiohttp.ClientSession(loop=loop) as session:
tasks = [fetch(session, url) for url in urls]
await asyncio.gather(*tasks)
return tasks
# time normal way of retrieval
if __name__ == '__main__':
urls = [a list of urls..]
loop = asyncio.get_event_loop()
details_async = loop.run_until_complete(main(loop, urls))
谢谢
【问题讨论】:
标签: python python-asyncio aiohttp