从QWebEngineProfile获取cookie作为字典 [英] Obtain cookies as dictionary from a QWebEngineProfile

查看:544
本文介绍了从QWebEngineProfile获取cookie作为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题确实说明了一切。想知道如何获取QWebEngineProfile的cookie作为其名称和值的字典或json格式。我正在使用PyQt5。

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 是管理cookie的类并且我们可以通过 cookieStore()方法访问此对象,为了获取cookie,可以通过 cookieAdded 信号,在下面的部分中,我们将显示一个示例:

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_())

这篇关于从QWebEngineProfile获取cookie作为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆