gpt4 book ai didi

python - 从 QWebEngineProfile 获取 cookie 作为字典

转载 作者:太空宇宙 更新时间:2023-11-03 14:17:41 28 4
gpt4 key购买 nike

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

最佳答案

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

关于python - 从 QWebEngineProfile 获取 cookie 作为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48150321/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com