【问题标题】:Python requests_html throwing error There is no current event loop in thread 'ThreadPoolExecutor-0_0'Python requests_html 抛出错误线程'ThreadPoolExecutor-0_0'中没有当前事件循环
【发布时间】:2021-06-04 08:37:29
【问题描述】:

我正在尝试使用 python requests_html 模块 为给定的 url 运行 JS script,但几乎没有错误。

有人能帮帮我吗?

代码:-

from requests_html import HTMLSession
def rrr(request):
    session = HTMLSession()
    url = 'https://careers.microsoft.com/'
    response = session.get(url)
    script = """
                () => {
                    return {
                        ans: window.location.href,
                    }
                }
            """
    ans = response.html.render(script=script)
    return JsonResponse(ans, safe=False)

错误:-

  File "/home/mahesh/anaconda3/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/home/mahesh/anaconda3/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/mahesh/anaconda3/lib/python3.7/site-packages/rest_framework/decorators.py", line 50, in handler
    return func(*args, **kwargs)
  File "/home/mahesh/Documents/dojo/dojo/dojo/tenants/api.py", line 242, in rrr
    ans = response.html.render(script=script)
  File "/home/mahesh/anaconda3/lib/python3.7/site-packages/requests_html.py", line 586, in render
    self.browser = self.session.browser  # Automatically create a event loop and browser
  File "/home/mahesh/anaconda3/lib/python3.7/site-packages/requests_html.py", line 727, in browser
    self.loop = asyncio.get_event_loop()
  File "/home/mahesh/anaconda3/lib/python3.7/asyncio/events.py", line 644, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'ThreadPoolExecutor-0_0'.

在终端运行时,运行良好,如下所示

【问题讨论】:

    标签: python django python-asyncio event-loop python-requests-html


    【解决方案1】:

    您是如何运行 RRR 的? asyncio 在多线程应用程序中很挑剔。需要更多信息

    【讨论】:

    • 你是如何在 python 上运行它的?
    • 我正在尝试在我的 Django 应用程序中将此函数作为 api 托管并获得响应
    • 没有帮助。但是我遇到了另一个给出相同错误响应的问题。您的主线程中没有正在运行的事件循环,这是我想与您确认的。
    • 哦....你能告诉我我还需要在这段代码中添加什么才能使其正常工作吗?
    • 是的......这是我在问题中发布的整个代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    相关资源
    最近更新 更多