我的目标是将QWebEngineView
cookie 保存到磁盘,以便如果打开该小部件的应用程序关闭,cookie 总是在应用程序退出之前可靠地保存到磁盘。这样,当再次执行应用程序时,它将使用上一次运行的 cookie 值开始。
使用下面的代码,将新的 cookie 值实际写入磁盘几乎需要一分钟。如果应用程序在此之前关闭,则根本不会将新的 cookie 值写入磁盘。
下面是一个示例程序,它使用 PyQt5 和 QWebEngineView 在 Windows 10 中打开一个网页,其中 cookie 保存到磁盘:
from pathlib import Path
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage, QWebEngineProfile
import sys
site = 'https://stackoverflow.com/search?q=pyqt5+forcepersistentcookies'
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
QMainWindow.__init__(self, *args, **kwargs)
self.webview = QWebEngineView()
profile = QWebEngineProfile.defaultProfile()
profile.setPersistentCookiesPolicy(QWebEngineProfile.ForcePersistentCookies)
browser_storage_folder = Path.home().as_posix() + '/.test_cookies'
profile.setPersistentStoragePath(browser_storage_folder)
webpage = QWebEnginePage(profile, self.webview)
self.webview.setPage(webpage)
self.webview.load(QUrl(site))
self.setCentralWidget(self.webview)
def closeEvent(self, event):
print('Close Event')
profile = QWebEngineProfile.defaultProfile()
profile.deleteLater()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
虽然上面的代码有效——如果你观察 Cookies 文件,你会看到它在页面加载后得到更新——页面加载后需要将近一分钟的时间才能在文件中更新 cookie:
C:\Users\<My User Account>\.test_cookies\Cookies
如果在此之前关闭窗口,更新的 cookie 将丢失。当 PyQt5 应用程序关闭时,如何强制 cookiestore 刷新到磁盘?我只能在 doc.qt.io找到一个提示,它说:
基于磁盘的 QWebEngineProfile 应该在应用程序退出时或之前销毁,否则缓存和持久数据可能不会完全刷新到磁盘。
没有提示如何在 Python 中销毁 QWebEngineProfile。调用del
变量不会做任何事情。调用deleteLater
配置文件也不会做任何事情。更改代码以创建一个全新的配置文件self.profile = QWebEngineProfile("storage", self.webview)
,在任何地方使用它,然后在closeEvent
调用self.profile.deleteLater()
中不会做任何事情。