【问题标题】:Using 'requests_html' with 'FastAPI'将“requests_html”与“FastAPI”一起使用
【发布时间】:2020-12-24 07:39:36
【问题描述】:

我正在尝试使用 requests_html 库和 js 渲染以及 FastAPI

脚本.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'.

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

【问题讨论】:

    标签: python python-3.x api fastapi python-requests-html


    【解决方案1】:

    你必须在 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
    
    

    【讨论】:

    • 效果很好,谢谢。我在第一次请求时也收到此警告``` .\scratch.py​​:13: RuntimeWarning: coroutine 'HTML.arender' is never awaited r.html.arender() RuntimeWarning: E​​nable tracemalloc to get the object allocation traceback `` `这是个问题吗?
    • 请将“r.html.arender()”替换为“await r.html.arender()”
    猜你喜欢
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多