Save and load cookies in Python with Selenium Web Driver
Hello programmers, in this tutorial we will see how to save and load the cookies using the selenium web driver in Python.
Cookies are small files with very small pieces of data which is saved by the browser while using an application. Cookies usually help in improving the user’s web browsing experience by analyzing data about the user’s experience over the application.
Data is only stored in cookies upon the user’s connection with the server. Cookies are very unique to the user’s computer.
Installation
Use the following command in your command prompt to download the Selenium web driver.
pip install selenium
Before running the code, we need to install the chrome driver and set it to our system path.
The file which is created can be found at C:/Users/<username>/AppData/Local/Google/Chrome/User Data/Default/Cookies/<filename.pkl>
Below is the demonstration for saving the cookies as a pickle file.
#Importing necessary Libraries import pickle from selenium import webdriver #save cookie function def seleniumSaveCookie(): #creating a webdriver object driver = webdriver.Chrome(executable_path='C:/path/to/dir/chromedriver.exe') driver.get("https://www.codespeedy.com/") #opening the url try: pickle.dump(driver.get_cookies(), open("cookie.pkl", "wb")) #writing in pickle file print('Cookie file successfully created.') except Exception as e: print(e) #driver if __name__ == "__main__": seleniumSaveCookie() #call the function
Output
Cookie file successfully created.
Explanation
We create an instance of chrome driver and open the URL. We write the cookies of the URL in ‘cookie.pkl’ file in binary mode. We use pickle as the required module here because it is used for serializing and de-serializing Python objects.
Below is the demonstration for loading the cookies.
#Importing necessary Libraries import pickle from selenium import webdriver #load cookie function def seleniumLoadCookie(): #creating a webdriver object driver = webdriver.Chrome(executable_path='C:/path/to/dir/chromedriver.exe') driver.get("https://www.codespeedy.com/") #opening the url try: cookie = pickle.load(open("cookie.pkl", "rb")) #loading from pickle file for i in cookie: driver.add_cookie(i) print('Cookies added.') except Exception as e: print(e) #driver if __name__ == "__main__": seleniumLoadCookie() #call the function
Output
Cookies added.
Explanation
We create an instance of chrome driver and open the URL. We read the ‘cookie.pkl’ file in binary mode and add it to the ‘cookie’ variable and then we add it to the driver object one by one.
Also read: Check if a page is completely loaded or not in Selenium web driver in Python
Leave a Reply