我尝试使用QT_WebBrowView登录网站,然后在登录后使用cookie按请求获取页面。所以我需要将QNetworkCookieJar直接转换为字符串dict或requests.cookie。 Blow是代码的相对片段。是否有某些功能可以这样做?
感谢。
环境:Python 3.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)
答案 0 :(得分:1)
我在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.')
答案 1 :(得分:1)
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)