Title explains it all really. Would like to know how to get the cookies of a QWebEngineProfile as a dictionary of their names and values or in a json format. I am using PyQt5.
QWebEngineCookieStore
is a class that manages cookies and we can access this object through the cookieStore()
method, in order to obtain cookies it can be done asynchronously through the cookieAdded
signal, in the following part we show an example:
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
QMainWindow.__init__(self, *args, **kwargs)
self.webview = QWebEngineView()
profile = QWebEngineProfile("storage", self.webview)
cookie_store = profile.cookieStore()
cookie_store.cookieAdded.connect(self.onCookieAdded)
self.cookies = []
webpage = QWebEnginePage(profile, self.webview)
self.webview.setPage(webpage)
self.webview.load(
QUrl("https://stackoverflow.com/questions/48150321/obtain-cookies-as-dictionary-from-a-qwebengineprofile"))
self.setCentralWidget(self.webview)
def onCookieAdded(self, cookie):
for c in self.cookies:
if c.hasSameIdentifier(cookie):
return
self.cookies.append(QNetworkCookie(cookie))
self.toJson()
def toJson(self):
cookies_list_info = []
for c in self.cookies:
data = {"name": bytearray(c.name()).decode(), "domain": c.domain(), "value": bytearray(c.value()).decode(),
"path": c.path(), "expirationDate": c.expirationDate().toString(Qt.ISODate), "secure": c.isSecure(),
"httponly": c.isHttpOnly()}
cookies_list_info.append(data)
print("Cookie as list of dictionary:")
print(cookies_list_info)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())