Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Requests Session Setting Cookie Key Error

I’m getting the cookies from selenium first after logging in and then adding the cookies to a requests session object. I get a key error and I don’t understand why. Here is my code:

cookies = driver.get_cookies()
s = requests.Session()
for cookie in cookies:
    for key, value in cookie.items():
        s.cookies.set(cookie[key], cookie[value])

Cookie looks like this:
{'domain': '.domain.com', 'expiry': 1666302866, 'httpOnly': False, 'name': '__utmb', 'path': '/', 'secure': False, 'value': '233684620.3.10.1666301065'}
The error in question is KeyError: ‘.domain.com’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

for key, value in cookie.items():
    s.cookies.set(cookie[key], cookie[value])

Since you are already iterating over the key-value pairs, cookie[value] makes no sense and is bound to fail, and cookie[key] gives back the value, not the key.

You need

for key, value in cookie.items():
    s.cookies.set(key, value)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading