如何解决使用 QWebEnginePage 运行时 Flask 应用程序崩溃
我用 PyQt5 QWebEnginePage 包编写了一个简单的 Flask 应用程序。我在 index.html
页面上有一个按钮。当我单击该按钮时,它将从 Google.com
获取文本并将其显示在下一页上。我正在使用 Beautiful Soup 来获取文本。
问题是第一次运行正常。但是,如果我返回并再次单击该按钮以从 Google 获取文本,则会在浏览器中显示此消息而崩溃。
这是我的代码。
app.py
from flask import Flask,render_template
from QApp import *
app = Flask(__name__)
@app.route('/')
def main():
return render_template('index.html')
@app.route('/runtest')
def run_test():
data = run_qapp()
return render_template("Qapp_test.html",data=data)
if __name__ == '__main__':
app.run(debug=True)
QApp.py
from bs4 import BeautifulSoup
import requests
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl,QCoreApplication
from PyQt5.QtWebEngineWidgets import QWebEnginePage
import sys
class Page(QWebEnginePage):
def __init__(self,url):
self.app = QCoreApplication.instance()
if self.app is None:
self.app = QApplication(sys.argv)
QWebEnginePage.__init__(self)
self.html = ''
self.loadFinished.connect(self._on_load_finished)
self.load(QUrl(url))
self.app.exec_()
def _on_load_finished(self):
self.html = self.toHtml(self.Callable)
def Callable(self,html_str):
self.html = html_str
self.app.quit()
def run_qapp():
page = Page('https://www.google.com/')
soup = BeautifulSoup(page.html,'html.parser')
return soup.text
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/runtest">
<input type="submit" value="Get Google Source">
</form>
</body>
</html>
Qapp_test.html
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ data }}
</body>
</html>
所以当我第一次单击按钮时,它起作用了,文本显示在下一页中。这是终端消息
127.0.0.1 - - [18/Mar/2021 18:14:15] "?[37mGET / HTTP/1.1?[0m" 200 -
WARNING: QApplication was not created in the main() thread.
[4364:16952:0318/181419.539:ERROR:cache_util_win.cc(21)] Unable to move the cache: Access is denied. (0x5)
[4364:16952:0318/181419.539:ERROR:cache_util.cc(139)] Unable to move cache folder C:\Users\abidh\AppData\Local\python\QtWebEngine
\Default\GPUCache to C:\Users\abidh\AppData\Local\python\QtWebEngine\Default\old_GPUCache_000
[4364:16952:0318/181419.539:ERROR:disk_cache.cc(184)] Unable to create cache
[4364:16952:0318/181419.539:ERROR:shader_disk_cache.cc(606)] Shader Cache Creation Failed: -2
[4364:16952:0318/181422.557:ERROR:service_worker_storage.cc(1575)] Failed to delete the database: Database IO error
127.0.0.1 - - [18/Mar/2021 18:14:25] "?[37mGET /runtest HTTP/1.1?[0m" 200 -
然后我单击浏览器的后退按钮并单击该按钮再次获取文本,应用程序崩溃了。这是我在终端收到的消息
WARNING: QApplication was not created in the main() thread.
你能帮我找出问题所在以及需要修复的地方吗?提前致谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。