Requests-html:在烧瓶上运行时出错 [英] Requests-html: error while running on flask
本文介绍了Requests-html:在烧瓶上运行时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我准备了一个使用 requests-html
运行良好的脚本.
I've prepared a script that was using requests-html
which was working fine.
我将它部署在 Flask 应用程序中,现在它给了我 RuntimeError: 线程 'Thread-3' 中没有当前事件循环.
I deployed it in the flask app and now it's giving me RuntimeError: There is no current event loop in thread 'Thread-3'.
这是完整的错误:
Traceback (most recent call last):
File "C:\Users\intel\AppData\Local\Programs\Python\Python38\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
.
.
.
File "C:\Users\intel\Desktop\One page\main.py", line 18, in hello_world
r.html.render()
File "C:\Users\intel\AppData\Local\Programs\Python\Python38\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\intel\AppData\Local\Programs\Python\Python38\Lib\site-packages\requests_html.py", line 727, in browser
self.loop = asyncio.get_event_loop()
File "C:\Users\intel\AppData\Local\Programs\Python\Python38\Lib\asyncio\events.py", line 639, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-3'.
这是原始代码:
from flask import Flask
from requests_html import HTMLSession
from bs4 import BeautifulSoup
app = Flask(__name__)
@app.route('/<user>')
def hello_world(user):
session = HTMLSession()
r = session.get('https://medium.com/@' + str(user))
print(r)
r.html.render()
divs = r.html.find('div')
lst = []
for div in divs:
soup = BeautifulSoup(div.html, 'html5lib')
div_tag = soup.find()
try:
title = div_tag.section.div.h1.a['href']
if title not in lst:
lst.append(title)
except:
pass
return "\n".join(lst)
if __name__ == '__main__':
app.run(debug=True)
推荐答案
你应该使用构建在 Flask 之上的 Quart 库.这将解决您的问题.
You should use Quart library built on top of flask. That will solve your problem.
安装:pip install quart
from quart import Quart
from requests_html import AsyncHTMLSession
app = Quart(__name__)
@app.route('/<user>')
def hello_world(user):
session = AsyncHTMLSession()
r = await session.get('https://medium.com/@' + str(user))
print(r)
await r.html.arender()
divs = r.html.find('div')
lst = []
for div in divs:
soup = BeautifulSoup(div.html, 'html5lib')
div_tag = soup.find()
try:
title = div_tag.section.div.h1.a['href']
if title not in lst:
lst.append(title)
except:
pass
这篇关于Requests-html:在烧瓶上运行时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文