The Python Oracle

Adding Cookies working with Firefox webdriver but not in PhantomJS

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Over Ancient Waters Looping

--

Chapters
00:00 Adding Cookies Working With Firefox Webdriver But Not In Phantomjs
00:31 Accepted Answer Score 7
01:01 Thank you

--

Full question
https://stackoverflow.com/questions/3710...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #selenium #cookies #webscraping #phantomjs

#avk47



ACCEPTED ANSWER

Score 7


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() :
            file.write(LINE.format(**cookie))

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


from selenium import webdriver

driver = webdriver.PhantomJS()

# load the domain
driver.get("https://stackoverflow.com/users/login")

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

# delete all the cookies
driver.delete_all_cookies()

# load the cookies from the file
load_cookies(driver, r"cookies.js")