How to save and load cookies using Python + Selenium WebDriver
You can save the current cookies as a Python object using pickle. For example:
import pickle
import selenium.webdriver
driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))
And later to add them back:
import pickle
import selenium.webdriver
driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
driver.add_cookie(cookie)
Save/Load Cookies with Python Selenium + Chrome
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.
How to get cookies saved in browser with python and Selenium
import pickle
import os
from selenium import webdriver
import time
option = webdriver.ChromeOptions()
option.add_argument("--no-sandbox")
driver = webdriver.Chrome(options=option)
driver.get("https://google.com")
time.sleep(5)
if os.path.exists('cookies.pkl'):
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
driver.add_cookie(cookie)
driver.refresh()
sleep(5)
pickle.dump(driver.get_cookies(), open("cookies.pkl", "wb"))
pickle will help you save and add cookies. But, be sure to add them to the correct domain otherwise you might get errors.
Related Topics
Word Boundary With Words Starting or Ending With Special Characters Gives Unexpected Results
Equivalent of Shell 'Cd' Command to Change the Working Directory
Changing One Character in a String
Difference Between Map, Applymap and Apply Methods in Pandas
Typeerror: Method() Takes 1 Positional Argument But 2 Were Given
What Does the "At" (@) Symbol Do in Python
Pip Install from Git Repo Branch
Python Function Global Variables
How Are Python'S Built in Dictionaries Implemented
Count the Frequency That a Value Occurs in a Dataframe Column
When Is "I += X" Different from "I = I + X" in Python
Adding a New Pandas Column With Mapped Value from a Dictionary
Permanently Add a Directory to Pythonpath
Remove Specific Characters from a String in Python