Rafael Almeida Rafael Almeida - 1 year ago 1219
Python Question

Adding Cookies working with Firefox webdriver but not in PhantomJS

I have a pickle with cookies that I create through the following command

def doLogin(driver):
#do login stuff
pickle.dump(driver.get_cookies(), open("cookies.pkl", "wb"))

I have the sample code to get the cookies

driver = webdriver.PhantomJS()
for cookie in pickle.load(open("cookies.pkl", "rb")):

I can see that it creates the cookie well because if I
it it's fine the add_cookie() is doing shady things

This gives the following exception

WebDriverException: Message: {"errorMessage":"Unable to set
\"391db430-154a-11e6-8a0a-ef59204729f5\", \"cookie\": {\"domain\":
\"secretWebsite\", \"name\": \"JSESSIONID\", \"value\":
\"8332B6099FA3BBBC82893D4C7E6E918B\", \"path\": \"Also a secret\",
\"httponly\": false, \"secure\":
Screenshot: available via screen

To work, all I need is to change webdriver to Firefox

Is this a known PhantomJS issue?

Answer Source

It seems that some key/values are not supported by the PhantomJS driver. To overcome this issue, I would inject the most important ones with execute_script:

def save_cookies(driver, file_path):
    LINE = "document.cookie = '{name}={value}; path={path}; domain={domain}; expires={expires}';\n"
    with open(file_path, 'w') as file :
        for cookie in driver.get_cookies() :

def load_cookies(driver, file_path):
    with open(file_path, 'r') as file:

from selenium import webdriver

driver = webdriver.PhantomJS()

# load the domain

# save the cookies to a file
save_cookies(driver, r"cookies.js")

# delete all the cookies

# load the cookies from the file
load_cookies(driver, r"cookies.js")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download