Is there a simple way to convert a cookiejar
from the Python 3 requests
library to a qnetworkcookiejar
?
I convert the cookiejar
from the requests library into a dictionary and then in a qnetworkcookiejar
. Some cookies are there in multiple versions with different values.
def updateCookieJar(self, cookiejar, requested_url):
qnetworkcookie_list = []
cookie_dict = dict_from_cookiejar(cookiejar)
for cookie in cookie_dict:
tmp_cookiejar = QNetworkCookie(cookie, cookie_dict[cookie])
qnetworkcookie_list.append(tmp_cookiejar)
qcookiejar = QNetworkCookieJar()
qcookiejar.setCookiesFromUrl(qnetworkcookie_list, QUrl(requested_url))
self.networkAccessManager().setCookieJar(qcookiejar)
This function is called inside a Webpage
.
The http. cookiejar module defines classes for automatic handling of HTTP cookies. It is useful for accessing web sites that require small pieces of data – cookies – to be set on the client machine by an HTTP response from a web server, and then returned to the server in later HTTP requests.
To send a request with a Cookie, you need to add the "Cookie: name=value" header to your request. To send multiple cookies in a single Cookie header, separate them with semicolons or add multiple "Cookie: name=value" request headers.
If, however, you are using an older model cookie jar, the answer is quite simple. Just put the cookies in a zip-style plastic bag, seal it up, and put the bag in the jar. Whenever you reach in for a cookie, it's an easy step to open the bag and close it back up to keep those cookies fresh.
Try using cookiejar
directly instead of dictionary.
def updateCookieJar(self, cookiejar, requested_url):
qnetworkcookie_list = []
for cookie in cookiejar:
tmp_cookiejar = QNetworkCookie(cookie.name, cookie.value)
qnetworkcookie_list.append(tmp_cookiejar)
qcookiejar = QNetworkCookieJar()
qcookiejar.setCookiesFromUrl(qnetworkcookie_list, QUrl(requested_url))
self.networkAccessManager().setCookieJar(qcookiejar)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With