gpt4 book ai didi

javascript - 运行时错误 : There is no current event loop in thread 'Thread-1' . - requests_html, html.render()

转载 作者:行者123 更新时间:2023-12-05 06:29:48 27 4
gpt4 key购买 nike

我正在尝试使用 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'.

最佳答案

与其在每次您想要执行请求时都启动一个计时器(并因此启动一个新线程),不如启动一个每 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)

关于javascript - 运行时错误 : There is no current event loop in thread 'Thread-1' . - requests_html, html.render(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53180478/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com