为什么错误是"Cannot use HTMLSession within an existing event loop. Use AsyncHTMLSession instead"?

Why is the error "Cannot use HTMLSession within an existing event loop. Use AsyncHTMLSession instead"?

我是运行@Dan-Dev 在他的.

中提供的代码
from requests_html import HTMLSession

url = 'https://www.thefreedictionary.com/love'
session = HTMLSession()
r = session.get(url)
r.html.render()
lang_bar = r.html.find('#LangBar', first=True)
print(lang_bar.html)

结果是

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-2-ec1d9137b197> in <module>
      8 
      9 resp = session.get(url, headers = headers)
---> 10 resp.html.render()
     11 
     12 soup = bs(resp.html.html, "lxml")

C:\Anaconda3\lib\site-packages\requests_html.py in render(self, retries, script, wait, scrolldown, sleep, reload, timeout, keep_page)
    584         """
    585 
--> 586         self.browser = self.session.browser  # Automatically create a event loop and browser
    587         content = None
    588 

C:\Anaconda3\lib\site-packages\requests_html.py in browser(self)
    727             self.loop = asyncio.get_event_loop()
    728             if self.loop.is_running():
--> 729                 raise RuntimeError("Cannot use HTMLSession within an existing event loop. Use AsyncHTMLSession instead.")
    730             self._browser = self.loop.run_until_complete(super().browser)
    731         return self._browser

RuntimeError: Cannot use HTMLSession within an existing event loop. Use AsyncHTMLSession instead.

显然,代码在 Dan-Dev 的计算机上运行良好。你能解释一下为什么我的笔记本电脑 returns 出错 Cannot use HTMLSession within an existing event loop. Use AsyncHTMLSession instead?

你可以试试这个:

import nest_asyncio

nest_asyncio.apply()

session = HTMLSession()
r = session.get("URL")

html_str = r.text

您可以将这些代码保存在源文件中,例如'src.py'。然后打开 Anaconda Prompt(假设你正在使用这个)和 运行 这个命令(确保你在包含 'src.py' 文件的文件夹中)

python src.py

这个解决方案对我有用。您不应该 运行 Spyder IDE 或 Jupyter Notebook 中的源文件。