Search code examples
pythonpython-2.7seleniumselenium-webdriverurllib2

strange exception in WebDrive when add_cookie is used


my code is something like that:

response = urllib2.urlopen(request)
cookieValue = response.info()["Set-Cookie"]
cookie = {'Set-Cookie': cookieValue}

driver = webdriver.Chrome()
driver.get(innerPageOfTheSameRequest)
print cookie
driver.add_cookie(cookie)

The cookie is printed as expected:

{'Set-Cookie': 'SessionID_R3=dXM0ChrdPhYUhfL1drI2eP9r6Wjha8tX943Sv8CZp0v6LQ2v1/m u3y/h839tX0zGJ36VtBsIY4EJaxlr78g9gokEfz6HA7wvXb7ECo8nRjXjO0+Ty/E5IC64BseItDk; pa th=/; HttpOnly;'}

But I get an excpetion on the last line:

Traceback (most recent call last): File "p.py", line 80, in driver.add_cookie(cookie) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 634, in add_cookie self.execute(Command.ADD_COOKIE, {'cookie': cookie_dict}) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 201, in execute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py" , line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: name of cookie is missing or invalid:"undefined" (Session info: chrome=48.0.2564.116) (Driver info: chromedriver=2.21.371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4),platform=Windows NT 6.1 SP1 x86_64)

Someone can help me to understand what I'm doing wrong ? Thanks


Solution

  • Your cookie doesn't have the right format. According to the documentation the argument to add_cookie() is

    cookie_dict: A dictionary object, with required keys - “name” and “value”;

    You have neither of these keys but instead have a Set-Cookie header.

    Your cookie should probably be

    {'name': SessionID_R3,
     'value' : 'dXM0ChrdPhYUhfL1drI2eP9r6Wjha8tX943Sv8CZp0v6LQ2v1/m u3y/h839tX0zGJ36VtBsIY4EJaxlr78g9gokEfz6HA7wvXb7ECo8nRjXjO0+Ty/E5IC64BseItDk',
     'path' : '/'}
    

    I'm not sure if you can get HttpOnly as it isn't mentioned in the documentation.