Requests-html: error while running on flask

本小妞迷上赌 提交于 2021-02-11 15:01:28

问题


I've prepared a script that was using requests-html which was working fine.

I deployed it in the flask app and now it's giving me RuntimeError: There is no current event loop in thread 'Thread-3'.

Here's the full error:

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

Here's the original code:

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)

来源:https://stackoverflow.com/questions/64690280/requests-html-error-while-running-on-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!