我正在尝试使用带有js渲染和FastAPI
的requests_html
库
script.py
from fastapi import FastAPI
from requests_html import HTMLSession
app = FastAPI()
@app.get('/')
def func():
with HTMLSession() as session:
r = session.get('https://stackoverflow.com')
r.html.render()
return r.text
当使用uvicorn script:app --reload
运行并访问http://127.0.0.1:8000/
时,我得到以下错误:
...
r.html.render()
File "c:\users\a\appdata\local\programs\python\python37\lib\site-packages\requests_html.py", line 586, in render
self.browser = self.session.browser # Automatically create a event loop and browser
File "c:\users\a\appdata\local\programs\python\python37\lib\site-packages\requests_html.py", line 727, in browser
self.loop = asyncio.get_event_loop()
File "c:\users\a\appdata\local\programs\python\python37\lib\asyncio\events.py", line 644, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'ThreadPoolExecutor-0_0'.
你知道怎样才能让他们一起工作吗?
发布于 2020-12-24 16:49:50
你必须在Uvicorn中使用AsyncHTMLSession
from fastapi import FastAPI
from requests_html import AsyncHTMLSession
app = FastAPI()
@app.get('/')
async def func():
asession = AsyncHTMLSession()
r = await asession.get('https://stackoverflow.org/')
await r.html.arender()
return r.text
https://stackoverflow.com/questions/65435377
复制相似问题