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

标签 javascript python

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

相关文章:

javascript - 如何从 Controller 返回 PDF 文件

python - 如何通过 C++ 在 Python 函数中传递字符串参数

python - Excel 等效于在 Python pandas 中使用的数组

javascript - 错误: TypeError: Cannot set property 'innerHTML' of null in phonegap

javascript - 仅在第一次加载 js 文件-在 angularjs : Making the ckeditor visible for first time only 中

javascript - Mac 上的 Google Chrome 本地存储

javascript - 为什么刷新页面后我的 WebSocket 连接会关闭?

python - 按键对列表进行排序并在不重新计算的情况下取出值

python加载带有引号字段的csv文件,其中逗号用作1000s分隔符

python - plotly 离线提供与在线版本相同吗?