Home > Software engineering >  Python Requests Session Setting Cookie Key Error
Python Requests Session Setting Cookie Key Error

Time:10-21

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'

CodePudding user response:

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)
  • Related