标题解释了这一切。想知道如何将QWebEngineProfile的cookie作为其名称和值的字典或以json格式获取。我正在使用PyQt5。 欢呼声。
答案 0 :(得分:1)
QWebEngineCookieStore
是一个管理cookie的类,我们可以通过cookieStore()
方法访问此对象,以获取cookie,它可以通过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_())