如何从 QNetworkCookieJar 转换为字符串字典或 requests.cookie?
How to convert from QNetworkCookieJar to a string dict or requests.cookie?
我尝试使用 QT_WebBrowView 登录网站,然后在登录后使用 cookie 按请求获取页面。所以我需要将 QNetworkCookieJar 直接转换为字符串字典或 requests.cookie 。 Blow是代码的相对片段。有什么功能可以做到吗?
谢谢。
环境:Python3.4.3 和 PyQT5。
import requests
from PyQt5 import QtCore, QtGui, QtWidgets, QtNetwork
self.QT_cookiejar_webbrowser = QtNetwork.QNetworkCookieJar()
self.QT_WebBrowView_wb.page().networkAccessManager().setCookieJar(self.QT_cookiejar_webbrowser)
def get_cookie(self):
QT_cookies = self.QT_cookiejar_webbrowser.allCookies()
print("QT_Cookies=%r" % QT_cookies)
for each_cookie in QT_cookies:
print("\n\n%r" % each_cookie)
QtCore.QStringListModel
# req = requests.get("http://www.baidu.com")
# req_cookie = req.cookies
# print("req_cookie=%r" % req_cookie)
我在 here 找到了一些代码。但它只适用于 Python2 和 PyQT4,不能单独使用 运行。我对其进行了一些更改以适合 PyQT5 和 python3。
现在你可以使用它在 PyQT 和 Python 之间转换 cookie 和 cookiejar 的格式。并保存到磁盘中的文件或从中加载文件。
如果您觉得有用,请点击左侧的有用按钮。 \^o^/
from http.cookiejar import Cookie, LWPCookieJar, CookieJar
from PyQt5.QtCore import QDateTime
from PyQt5.QtNetwork import QNetworkCookie, QNetworkCookieJar
class QT5_Py_Cookie(object):
@staticmethod
def toQtCookie(PyCookie):
qc = QNetworkCookie(PyCookie.name, PyCookie.value)
qc.setSecure(PyCookie.secure)
if PyCookie.path_specified:
qc.setPath(PyCookie.path)
if PyCookie.domain != "":
qc.setDomain(PyCookie.domain)
if PyCookie.expires and PyCookie.expires != 0:
t = QDateTime()
t.setTime_t(PyCookie.expires)
qc.setExpirationDate(t)
# not yet handled(maybe less useful):
# py cookie.rest / QNetworkCookie.setHttpOnly()
return qc
@staticmethod
def toPyCookie(QtCookie):
port = None
port_specified = False
secure = QtCookie.isSecure()
name = QtCookie.name().data().decode()
value = QtCookie.value().data().decode()
v = QtCookie.path()
path_specified = bool(v != "")
path = v if path_specified else None
v = QtCookie.domain()
domain_specified = bool(v != "")
domain = v
if domain_specified:
domain_initial_dot = v.startswith('.')
else:
domain_initial_dot = None
v = int(QtCookie.expirationDate().toTime_t())
expires = 2147483647 if v > 2147483647 else v
rest = {"HttpOnly": QtCookie.isHttpOnly()}
discard = False
return Cookie(
0,
name,
value,
port,
port_specified,
domain,
domain_specified,
domain_initial_dot,
path,
path_specified,
secure,
expires,
discard,
None,
None,
rest,
)
def toPyCookieJar(self, QtCookieJar, PyCookieJar):
for c in QtCookieJar.allCookies():
PyCookieJar.set_cookie(self.toPyCookie(c))
def toQtCookieJar(self, PyCookieJar, QtCookieJar, keep_old=False):
allCookies = QtCookieJar.allCookies() if keep_old else []
for pc in PyCookieJar:
qc = self.toQtCookie(pc)
allCookies.append(qc)
QtCookieJar.setAllCookies(allCookies)
def load_cookies(self, cookie_storage, keep_old=False):
"""load from cookielib's CookieJar or Set-Cookie3 format text file.
:param cookie_storage: file location string on disk or CookieJar
instance.
:param keep_old: Don't reset, keep cookies not overridden.
"""
cookie_jar = QNetworkCookieJar()
if cookie_storage.__class__.__name__ == 'str':
cj = LWPCookieJar(cookie_storage)
cj.load()
self.toQtCookieJar(cj, cookie_jar)
elif cookie_storage.__class__.__name__.endswith('CookieJar'):
self.toQtCookieJar(cookie_storage, cookie_jar, keep_old)
else:
raise ValueError('unsupported cookie_storage type.')
return cookie_jar
def save_cookies(self, cookie_storage, cookie_jar):
"""Save to http.cookiejar's CookieJar or Set-Cookie3 format text file.
:param cookie_storage: file location string or CookieJar instance.
:param cookie_jar: http.cookiejar's Cookiejar for save.
"""
if cookie_storage.__class__.__name__ == 'str':
cj = LWPCookieJar(cookie_storage)
self.toPyCookieJar(cookie_jar, cj)
cj.save()
elif cookie_storage.__class__.__name__.endswith('CookieJar'):
self.toPyCookieJar(cookie_jar, cookie_storage)
else:
raise ValueError('unsupported cookie_storage type.')
qtNetworkCookies = self.QT_cookiejar_webbrowser.cookiesForUrl(url)
cookies = RequestsCookieJar()
for qtNetworkCookie in qtNetworkCookies:
cookie = requests.cookies.create_cookie(name=str(qtNetworkCookie.name(), 'utf-8'), value=str(qtNetworkCookie.value(), 'utf-8'))
cookie.domain = ".google.com" #your domain
cookies.set_cookie(cookie)
我尝试使用 QT_WebBrowView 登录网站,然后在登录后使用 cookie 按请求获取页面。所以我需要将 QNetworkCookieJar 直接转换为字符串字典或 requests.cookie 。 Blow是代码的相对片段。有什么功能可以做到吗?
谢谢。
环境:Python3.4.3 和 PyQT5。
import requests
from PyQt5 import QtCore, QtGui, QtWidgets, QtNetwork
self.QT_cookiejar_webbrowser = QtNetwork.QNetworkCookieJar()
self.QT_WebBrowView_wb.page().networkAccessManager().setCookieJar(self.QT_cookiejar_webbrowser)
def get_cookie(self):
QT_cookies = self.QT_cookiejar_webbrowser.allCookies()
print("QT_Cookies=%r" % QT_cookies)
for each_cookie in QT_cookies:
print("\n\n%r" % each_cookie)
QtCore.QStringListModel
# req = requests.get("http://www.baidu.com")
# req_cookie = req.cookies
# print("req_cookie=%r" % req_cookie)
我在 here 找到了一些代码。但它只适用于 Python2 和 PyQT4,不能单独使用 运行。我对其进行了一些更改以适合 PyQT5 和 python3。 现在你可以使用它在 PyQT 和 Python 之间转换 cookie 和 cookiejar 的格式。并保存到磁盘中的文件或从中加载文件。 如果您觉得有用,请点击左侧的有用按钮。 \^o^/
from http.cookiejar import Cookie, LWPCookieJar, CookieJar
from PyQt5.QtCore import QDateTime
from PyQt5.QtNetwork import QNetworkCookie, QNetworkCookieJar
class QT5_Py_Cookie(object):
@staticmethod
def toQtCookie(PyCookie):
qc = QNetworkCookie(PyCookie.name, PyCookie.value)
qc.setSecure(PyCookie.secure)
if PyCookie.path_specified:
qc.setPath(PyCookie.path)
if PyCookie.domain != "":
qc.setDomain(PyCookie.domain)
if PyCookie.expires and PyCookie.expires != 0:
t = QDateTime()
t.setTime_t(PyCookie.expires)
qc.setExpirationDate(t)
# not yet handled(maybe less useful):
# py cookie.rest / QNetworkCookie.setHttpOnly()
return qc
@staticmethod
def toPyCookie(QtCookie):
port = None
port_specified = False
secure = QtCookie.isSecure()
name = QtCookie.name().data().decode()
value = QtCookie.value().data().decode()
v = QtCookie.path()
path_specified = bool(v != "")
path = v if path_specified else None
v = QtCookie.domain()
domain_specified = bool(v != "")
domain = v
if domain_specified:
domain_initial_dot = v.startswith('.')
else:
domain_initial_dot = None
v = int(QtCookie.expirationDate().toTime_t())
expires = 2147483647 if v > 2147483647 else v
rest = {"HttpOnly": QtCookie.isHttpOnly()}
discard = False
return Cookie(
0,
name,
value,
port,
port_specified,
domain,
domain_specified,
domain_initial_dot,
path,
path_specified,
secure,
expires,
discard,
None,
None,
rest,
)
def toPyCookieJar(self, QtCookieJar, PyCookieJar):
for c in QtCookieJar.allCookies():
PyCookieJar.set_cookie(self.toPyCookie(c))
def toQtCookieJar(self, PyCookieJar, QtCookieJar, keep_old=False):
allCookies = QtCookieJar.allCookies() if keep_old else []
for pc in PyCookieJar:
qc = self.toQtCookie(pc)
allCookies.append(qc)
QtCookieJar.setAllCookies(allCookies)
def load_cookies(self, cookie_storage, keep_old=False):
"""load from cookielib's CookieJar or Set-Cookie3 format text file.
:param cookie_storage: file location string on disk or CookieJar
instance.
:param keep_old: Don't reset, keep cookies not overridden.
"""
cookie_jar = QNetworkCookieJar()
if cookie_storage.__class__.__name__ == 'str':
cj = LWPCookieJar(cookie_storage)
cj.load()
self.toQtCookieJar(cj, cookie_jar)
elif cookie_storage.__class__.__name__.endswith('CookieJar'):
self.toQtCookieJar(cookie_storage, cookie_jar, keep_old)
else:
raise ValueError('unsupported cookie_storage type.')
return cookie_jar
def save_cookies(self, cookie_storage, cookie_jar):
"""Save to http.cookiejar's CookieJar or Set-Cookie3 format text file.
:param cookie_storage: file location string or CookieJar instance.
:param cookie_jar: http.cookiejar's Cookiejar for save.
"""
if cookie_storage.__class__.__name__ == 'str':
cj = LWPCookieJar(cookie_storage)
self.toPyCookieJar(cookie_jar, cj)
cj.save()
elif cookie_storage.__class__.__name__.endswith('CookieJar'):
self.toPyCookieJar(cookie_jar, cookie_storage)
else:
raise ValueError('unsupported cookie_storage type.')
qtNetworkCookies = self.QT_cookiejar_webbrowser.cookiesForUrl(url)
cookies = RequestsCookieJar()
for qtNetworkCookie in qtNetworkCookies:
cookie = requests.cookies.create_cookie(name=str(qtNetworkCookie.name(), 'utf-8'), value=str(qtNetworkCookie.value(), 'utf-8'))
cookie.domain = ".google.com" #your domain
cookies.set_cookie(cookie)