使用 'requests_html' 和 'FastAPI'
Using 'requests_html' with 'FastAPI'
我正在尝试将 requests_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://whosebug.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'.
知道如何让它们协同工作吗?
你必须在 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://Whosebug.org/')
await r.html.arender()
return r.text
我正在尝试将 requests_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://whosebug.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'.
知道如何让它们协同工作吗?
你必须在 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://Whosebug.org/')
await r.html.arender()
return r.text