Adding Cookies working with Firefox webdriver but not in PhantomJS

守給你的承諾、 提交于 2019-12-03 16:42:20

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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!