[英]RuntimeError: There is no current event loop in thread 'Thread-1'. - requests_html, html.render()
I'm trying to render a HTML page in every 10 secs in Python with Requests-HTML module. 我正在尝试使用Requests-HTML模块在Python中每10秒渲染一次HTML页面。 For the first run it works perfectly, but after it crashes, with the error message below.
对于第一次运行,它可以正常运行,但是在崩溃后,显示以下错误消息。 My partial code is:
我的部分代码是:
def get_data_from_page():
session = HTMLSession()
r = session.get('https://something.com/')
threading.Timer(10.0, get_data_from_page).start()
r.html.render()
#code continues
def main():
get_data_from_page()
if __name__ == '__main__':
main()
Error message is: 错误信息是:
Exception in thread Thread-1:
File "/home/david/.local/lib/python3.6/site-packages/requests_html.py", line 572, in render
self.session.browser # Automatycally create a event loop and browser
File "/home/david/.local/lib/python3.6/site-packages/requests_html.py", line 679, in browser
self.loop = asyncio.get_event_loop()
File "/usr/lib/python3.6/asyncio/events.py", line 694, in get_event_loop
return get_event_loop_policy().get_event_loop()
File "/usr/lib/python3.6/asyncio/events.py", line 602, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-1'.
Instead of starting a timer (and thus a new thread) each time you want to do a request, it would probably be better to just start one thread that does the request every 10 seconds. 而不是每次要执行请求时都启动计时器(并因此启动新线程),最好仅启动一个每10秒执行一次请求的线程。
For example: 例如:
class RequestThread(Thread):
def __init__(self):
super().__init__()
self.stop = Event()
def run(self):
while not self.stop.wait(10):
session = HTMLSession()
r = session.get('https://something.com/')
r.html.render()
def stop(self):
self.stop.set()
However, it seems requests_html is very thread unfriendly (it uses signals among other things). 但是,requests_html似乎对线程非常不友好(除其他外,它还使用信号)。 So you must run this in the main thread and create a thread for anything else you want to do.
因此,您必须在主线程中运行此代码,并为其他任何您想做的事情创建一个线程。 Something like this seems to work:
像这样的事情似乎起作用:
import requests_html
import time
def get_data_from_page():
print(time.time())
session = requests_html.HTMLSession()
r = session.get('https://google.com')
r.html.render()
while True:
next_time = time.time() + 10
get_data_from_page()
wait_for = next_time - time.time()
if wait_for > 0:
time.sleep(wait_for)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.