我正在尝试使用Requests-HTML模块在Python中每10秒呈现一次HTML页面。对于第一次运行,它可以正常运行,但是在崩溃后,显示以下错误消息。我的部分代码是:
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()
错误消息是:
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'.
答案 0 :(得分:0)
与其每次要执行一个请求都不会启动计时器(因此也不会启动一个新线程),不如只是启动一个每10秒执行一次请求的线程。
例如:
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()
但是,requests_html似乎对线程非常不友好(除其他外,它还使用信号)。因此,您必须在主线程中运行此代码,并为其他任何您想做的事情创建一个线程。像这样的事情似乎起作用:
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)