简体   繁体   中英

Save/Load Cookies with Python Selenium + Chrome

I'd like to ask for a 2021 code revision of this old question: How to save and load cookies using Python + Selenium WebDriver

I'm specifically interested in the solution using Chrome to automatically manage your cookies in separate profile folders.

My objective is to have a folder on desktop as a standalone virtual environment, so all cookies will be saved in that folder and loaded from that same folder the next time you launch a Selenium instance.

In an effort to find the cleanest solution, I stumbled upon these code snippets:

chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")

This first solution doesn't work for me. I was given a deprecation warning for "chrome_options", so changed that to just "options", but the code still doesn't work throwing some errors.

options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(executable_path=r'C:\chromedriver_win32\chromedriver.exe', options=options)

What I can't understand here is the difference between using "ChromeOptions()" rather than "Options()". I also don't get why the path is passed directly as an argument instead of using "options.add_argument".

As I said at the beginning, I'm striving to find the cleanest solution for storing/loading cookies in a separate folder environment using Python Selenium + Chrome. This of course implies using the latest syntax updated to 2021.

from selenium.webdriver.chrome.options import Options
from selenium import webdriver
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.google.com")

You'd have to use options like so otherwise you'd get a depreciation warning from chrome options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM