Skip to content

Commit 84f3a7e

Browse files
committed
设置Cookie #155
1 parent 0c8e7d3 commit 84f3a7e

File tree

4 files changed

+112
-5
lines changed

4 files changed

+112
-5
lines changed

QWebEngineView/README.md

+10-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
- [同网站不同用户](#4同网站不同用户)
88
- [拦截请求](#5拦截请求)
99
- [拦截请求内容](#6拦截请求内容)
10+
- [设置Cookie](#7设置Cookie)
1011

1112
## 1、获取Cookie
1213
[运行 GetCookie.py](GetCookie.py)
@@ -52,4 +53,12 @@
5253
这里用了一个投巧的办法,原理是先通过`QWebEngineUrlRequestInterceptor`中的`interceptRequest`方法对每个请求做拦截过滤,
5354
发现目标url后重定向到`QWebEngineUrlSchemeHandler`实现的自定义协议头返回数据
5455

55-
![BlockRequestData](ScreenShot/BlockRequestData.png)
56+
![BlockRequestData](ScreenShot/BlockRequestData.png)
57+
58+
## 7、设置Cookie
59+
[运行 SetCookies.py](SetCookies.py)
60+
61+
通过`QWebEngineProfile`中得到的`cookieStore`来添加`QNetworkCookie`对象实现,
62+
需要注意的是httpOnly=true时,通过js无法获取
63+
64+
![SetCookies](ScreenShot/SetCookies.png)
72.8 KB
Loading

QWebEngineView/SetCookies.py

+97
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
"""
4+
Created on 2022/05/12
5+
@author: Irony
6+
@site: https://pyqt.site https://github.com/PyQt5
7+
@email: 892768447@qq.com
8+
@file: SetCookies.py
9+
@description: 主动设置Cookie
10+
"""
11+
12+
try:
13+
from PyQt5.QtCore import QDateTime, Qt, QUrl
14+
from PyQt5.QtWebEngineWidgets import QWebEngineProfile, QWebEngineView
15+
from PyQt5.QtWidgets import QApplication
16+
from PyQt5.QtNetwork import QNetworkCookie
17+
except ImportError:
18+
from PySide2.QtCore import QDateTime, Qt, QUrl
19+
from PySide2.QtWebEngineWidgets import QWebEngineProfile, QWebEngineView
20+
from PySide2.QtWidgets import QApplication
21+
from PySide2.QtNetwork import QNetworkCookie
22+
23+
cookies = [{
24+
"domain": "pyqt.site",
25+
"expirationDate": 1714906174.734258,
26+
"hostOnly": True,
27+
"httpOnly": False,
28+
"name": "snexid",
29+
"path": "/",
30+
"sameSite": None,
31+
"secure": False,
32+
"session": False,
33+
"storeId": None,
34+
"value": "1-22-333-4444-55555"
35+
}, {
36+
"domain": "pyqt.site",
37+
"expirationDate": 1714906174.734258,
38+
"hostOnly": True,
39+
"httpOnly": True,
40+
"name": "testonly",
41+
"path": "/",
42+
"secure": True,
43+
"value": "testonly"
44+
}, {
45+
"domain": "pyqt.site",
46+
"hostOnly": True,
47+
"httpOnly": False,
48+
"name": "test",
49+
"path": "/",
50+
"secure": False,
51+
"value": "test"
52+
}]
53+
54+
55+
class Window(QWebEngineView):
56+
57+
def __init__(self, *args, **kwargs):
58+
super(Window, self).__init__(*args, **kwargs)
59+
# global
60+
# self.cookieStore = QWebEngineProfile.defaultProfile().cookieStore()
61+
62+
# current
63+
self.cookieStore = self.page().profile().cookieStore()
64+
self.initCookies()
65+
self.loadProgress.connect(self.onLoadProgress)
66+
self.load(QUrl('https://pyqt.site'))
67+
68+
def onLoadProgress(self, progress):
69+
if progress == 100:
70+
# 测试获取cookie
71+
self.page().runJavaScript('alert(document.cookie);')
72+
73+
def initCookies(self):
74+
for cookie in cookies:
75+
qcookie = QNetworkCookie()
76+
qcookie.setName(cookie.get('name', '').encode())
77+
qcookie.setValue(cookie.get('value', '').encode())
78+
qcookie.setDomain(cookie.get('domain', ''))
79+
qcookie.setPath(cookie.get('path', ''))
80+
qcookie.setExpirationDate(
81+
QDateTime.fromString(str(cookie.get('expirationDate', 0)),
82+
Qt.ISODate))
83+
qcookie.setHttpOnly(cookie.get('httpOnly', False))
84+
qcookie.setSecure(cookie.get('secure', False))
85+
# 注意可以设置具体的url
86+
self.cookieStore.setCookie(qcookie, QUrl())
87+
88+
89+
if __name__ == '__main__':
90+
import cgitb
91+
import sys
92+
93+
cgitb.enable(format='text')
94+
app = QApplication(sys.argv)
95+
w = Window()
96+
w.show()
97+
sys.exit(app.exec_())

README.md

+5-4
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ https://pyqt.site 论坛是专门针对PyQt5学习和提升开设的网站,分
1717

1818
[自定义控件](https://github.com/PyQt5/CustomWidgets)
1919

20+
# QQ群
21+
22+
[PyQt 学习](https://jq.qq.com/?_wv=1027&k=5QVVEdF)
23+
2024
## 目录
2125

2226
- Layouts
@@ -151,6 +155,7 @@ https://pyqt.site 论坛是专门针对PyQt5学习和提升开设的网站,分
151155
- [同网站不同用户](QWebEngineView/SiteDiffUser.py)
152156
- [拦截请求](QWebEngineView/BlockRequest.py)
153157
- [拦截请求内容](QWebEngineView/BlockRequestData.py)
158+
- [设置Cookie](QWebEngineView/SetCookies.py)
154159
- [浏览器下载文件](Test/partner_625781186/6.QWebEngineView下载文件)
155160
- [打印网页](Test/partner_625781186/17_打印预览qwebengineview)
156161
- [QWebChannel](QWebChannel)
@@ -271,10 +276,6 @@ https://pyqt.site 论坛是专门针对PyQt5学习和提升开设的网站,分
271276
- [屏幕变动监听](Demo/ScreenNotify.py)
272277
- [无边框窗口](Demo/NewFramelessWindow.py)
273278

274-
# QQ群
275-
276-
[PyQt 学习](https://jq.qq.com/?_wv=1027&k=5QVVEdF)
277-
278279

279280
# [Donate-打赏](Donate)
280281

0 commit comments

Comments
 (0)