Python 使用';请求html';与';FastAPI';

Python 使用';请求html';与';FastAPI';,python,python-3.x,api,fastapi,python-requests-html,Python,Python 3.x,Api,Fastapi,Python Requests Html,我正在尝试将请求\u html库与js呈现一起使用FastAPI: 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')

我正在尝试将
请求\u html
库与js呈现一起使用
FastAPI

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脚本运行时:应用程序--重新加载
并访问
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'.


知道如何让它们一起工作吗?

您必须在Uvicorn中使用AsyncHTMLSession

从fastapi导入fastapi
从请求\u html导入异步HtmlSession
app=FastAPI()
@app.get(“/”)
异步def func():
asession=AsyncHTMLSession()
r=等待会话。获取('https://stackoverflow.org/')
等待r.html.arender()
返回r.text

效果很好,谢谢你。我在第一个请求``.\scratch.py:13:RuntimeWarning:coroutine'HTML.arender'从未等待过r.HTML.arender()RuntimeWarning:Enable tracemalloc获取对象分配回溯``这是一个问题吗?请将“r.HTML.arender()”替换为“wait r.HTML.arender()”