首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将“requests_html”与“FastAPI”一起使用

将“requests_html”与“FastAPI”一起使用
EN

Stack Overflow用户
提问于 2020-12-24 15:39:37
回答 1查看 248关注 0票数 0

我正在尝试使用带有js渲染和FastAPIrequests_html

script.py

代码语言:javascript
运行
复制
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/时,我得到以下错误:

代码语言:javascript
运行
复制
...
 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'.

你知道怎样才能让他们一起工作吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-24 16:49:50

你必须在Uvicorn中使用AsyncHTMLSession

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65435377

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档