【问题标题】:Obtain cookies as dictionary from a QWebEngineProfile从 QWebEngineProfile 获取 cookie 作为字典
【发布时间】:2018-06-17 10:24:05
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x cookies pyqt5 qtwebengine


    【解决方案1】:

    QWebEngineCookieStore是一个管理cookies的类,我们可以通过cookieStore()方法访问这个对象,为了获取cookies可以通过cookieAdded信号异步完成,下面我们举个例子:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 2023-03-31
      • 1970-01-01
      • 2017-07-15
      相关资源
      最近更新 更多