我想使用 asyncio 获取网页 html。
我在 jupyter notebook 中运行以下代码:
import aiofiles
import aiohttp
from aiohttp import ClientSession
async def get_info(url, session):
resp = await session.request(method="GET", url=url)
resp.raise_for_status()
html = await resp.text(encoding='GB18030')
with open('test_asyncio.html', 'w', encoding='utf-8-sig') as f:
f.write(html)
return html
async def main(urls):
async with ClientSession() as session:
tasks = [get_info(url, session) for url in urls]
return await asyncio.gather(*tasks)
if __name__ == "__main__":
url = ['http://huanyuntianxiazh.fang.com/house/1010123799/housedetail.htm', 'http://zhaoshangyonghefu010.fang.com/house/1010126863/housedetail.htm']
result = asyncio.run(main(url))
但是,它返回 RuntimeError: asyncio.run() cannot be called from a running event loop
问题是什么?
如何解决?
原文由 Chan 发布,翻译遵循 CC BY-SA 4.0 许可协议
asyncio.run()
文档说:在您的情况下,jupyter( IPython ≥ 7.0 )已经在运行事件循环:
因此,您不需要自己启动事件循环,而是可以直接调用
await main(url)
,即使您的代码位于任何异步函数之外。木星 / IPython
Python (≥ 3.7) 或旧版本的 IPython
在你的代码中会给出:
警告
与 IPython 相比,Jupyter 使用循环的方式 略有不同。