gpt4 book ai didi

python - "RuntimeError: There is no current event loop in thread ' Thread- 2'."错误是什么意思?

转载 作者:行者123 更新时间:2023-12-05 03:41:52 25 4
gpt4 key购买 nike

所以我一直在尝试使用 pyppeteer 制作一个简单的比特币价格检查器。它工作得很好,但每当我尝试将它实现到 flask 时,我都会遇到运行时错误。

本质上,我想构建一个 web api 调用,每当我单击一个按钮时,它就会调用 webscraper 文件。

如果有人能帮助指导我,那将不胜感激!

flask 服务器

import webscraper
import asyncio

from flask import Flask, redirect, url_for, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
return render_template('index.html', title="Home")

@app.route('/api/scrape', methods=['POST'])
def scrape():
webscraper.crypto_price('https://coinmarketcap.com/currencies/bitcoin/')
return redirect(url_for('index'))

if(__name__ == '__main__'):
app.run()

Pyppeteer 文件

import asyncio
from pyppeteer import browser, launch

def write_to_file(file, text):
f = open(file, 'w')
f.write(text)
f.close

def crypto_price(link):
async def main():
browser = await launch()
page = await browser.newPage()
await page.setViewport({'width': 1920, 'height': 1080})

await page.goto(link, {'waitUntil': 'networkidle2'})
data = await page.evaluate('''()=> {
return {
price: document.querySelector('#__next > div > div.main-content > div.sc-57oli2-0.dEqHl.cmc-body-wrapper > div > div.sc-16r8icm-0.hNsOU.container > div.sc-16r8icm-0.kXPxnI.container___lbFzk > div.sc-16r8icm-0.kXPxnI.priceSection___3kA4m > div.sc-16r8icm-0.kXPxnI.priceTitle___1cXUG > div').innerText
}
}''')

await browser.close()

write_to_file('./webscrape_result.txt', data['price'])

asyncio.get_event_loop().run_until_complete(main())

错误

[2021-05-14 09:30:15,007] ERROR in app: Exception on /api/scrape [POST]
Traceback (most recent call last):
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\gabri\Desktop\Python Web Scraper\server.py", line 14, in scrape
webscraper.crypto_price('https://coinmarketcap.com/currencies/bitcoin/')
File "C:\Users\gabri\Desktop\Python Web Scraper\webscraper.py", line 26, in crypto_price
asyncio.get_event_loop().run_until_complete(main())
File "C:\Users\gabri\AppData\Local\Programs\Python\Python39\lib\asyncio\events.py", line 642, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-2'.

最佳答案

您正在尝试在主线程以外的某个线程中运行 asyncio.get_event_loop() - 但是,asyncio 只会为主线程生成一个事件循环。

改为使用 new_event_loop:

asyncio.new_event_loop().run_until_complete(main())

关于python - "RuntimeError: There is no current event loop in thread ' Thread- 2'."错误是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67537746/

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