How to save and load cookies in Selenium using Python
Last Updated :
07 Oct, 2024
In web automation and testing, maintaining session information across different runs of scripts is often necessary. Cookies are a great way to save session data to avoid logging in repeatedly. Selenium, a popular tool for web testing, provides straightforward ways to save and load cookies using Python.
In this article, we will learn all the steps to handle cookies efficiently in Selenium.
Working with Cookies in Selenium
A cookie is a small piece of data that is sent from a website/server and stored on our computer. Cookies are mostly used to recognize the user and load the stored information. We can add, delete, and read cookies, which makes it convenient to manage sessions.
Key operations with cookies in Selenium:
- Adding a Cookie: Add a cookie to the current session using the add_cookie() method.
- Getting All Cookies: Retrieve all cookies stored in the current session with the get_cookies() method.
- Deleting Cookies: Remove cookies from the session using the delete_cookie() method.
1. Saving Cookies to `cookies.pkl`
In order to maintain the session details, we can write cookies into a file. This comes in handy when it becomes necessary to carry on with a session without signing back in.
The following code snippet saves cookies to a file after logging into a website:
Python
import undetected_chromedriver as uc
import pickle
driver = uc.Chrome()
driver.get('https://geeksforgeeks.org')
# Perform actions (e.g., log in)
# ...
cookies = driver.get_cookies()
print(cookies)
with open('cookies.pkl', 'wb') as file:
pickle.dump(cookies, file)
print("Cookies saved successfully.")
# Close the browser
driver.quit()
Output: We get a cookies.pkl file in the current working directory. This file contains the saved cookies in binary format.
cookies.pkl
Saving cookies using Python Selenium2. Loading Cookies from cookies.pkl
To resume a session, we can load cookies from a file and add them back to the browser using Selenium.
The following code snippet loads cookies from a file and uses them to restore the session:
- Load Cookies: Read the
cookies.pkl
file and load the cookies into the browser using driver.add_cookie()
. - Refresh the Page: Refresh the browser to apply the loaded cookies.
Python
import undetected_chromedriver as uc
import pickle
driver = uc.Chrome()
driver.get('https://geeksforgeeks.org')
# Load cookies from a file
with open('cookies.pkl', 'rb') as file:
cookies = pickle.load(file)
for cookie in cookies:
driver.add_cookie(cookie)
# Refresh the page to apply the cookies
driver.refresh()
# We can continue with our automation
# ...
# Close the browser
driver.quit()
3. Saving Cookies to cookies.json
Instead of using pickle
, we can use Python's json
module to save the cookies in a human-readable cookies.json
file.
Python
import undetected_chromedriver as uc
import json
driver = uc.Chrome()
driver.get('https://geeksforgeeks.org')
# Perform actions (e.g., log in)
# ...
# Save cookies to a JSON file
cookies = driver.get_cookies()
with open('cookies.json', 'w') as file:
json.dump(cookies, file)
# Close the browser
driver.quit()
Output:
Saving cookies in json in selenium python4. Loading Cookies from cookies.json
We can use json.load()
to read the cookies from the cookies.json
file and load them into the browser as before.
To load cookies from a cookies.json
file, use the following code:
Python
import undetected_chromedriver as uc
import json
driver = uc.Chrome()
driver.get('https://geeksforgeeks.org')
# Load cookies from a JSON file
with open('cookies.json', 'r') as file:
cookies = json.load(file)
for cookie in cookies:
driver.add_cookie(cookie)
# Refresh the page to apply the cookies
driver.refresh()
# We can continue with our automation
# ...
# Close the browser
driver.quit()
Best Practices
- Secure Storage: In particular, when it comes to sensitive data stored in cookies make sure to secure them properly. Do not allow this data to be accessed from source control or logs.
- Cookie Expiration: Refer to the expiration date prior to loading cookies to manage cookie expiration. If they aren’t working anymore, re-authenticate and save new ones.
- SameSite attribute: Ensure that when utilizing cookies across varying domains to prevent probable difficulties with sharing of cookies.
Conclusion
The strategy comprising Storage as well as Load cookies in Selenium using Python is simple but it is a very powerful technique for managing sessions during web tests. If cookies are kept persistently one will not have to log in again and again because all the automation will be easy. This method suits particularly those test scripts which have to preserve a session state after many executions.
Similar Reads
How to save and load cookies in Selenium using java?
Selenium WebDriver is a powerful tool that automates web application testing. One of the critical aspects of web automation is handling cookies, which are used to store information like user sessions and authentication tokens. By learning to save and load cookies in Selenium using Java, you can main
4 min read
How to use close() and quit() method in Selenium Python ?
While doing stuff with selenium multiple browsers with multiple tabs will normally opens in order to close these tabs close() and quit() methods are used. close() method is used to close the current browser window on which the focus is set, on the other hand quit() method essentially calls the drive
2 min read
How to move back and forward in History using Selenium Python ?
Seleniumâs Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout â Navigating links using get method â Selenium Python. Just bein
2 min read
How to Locate Elements using Selenium Python?
Selenium: is an open-source tool that automates web browsers. It provides a single interface that lets you write test scripts in programming languages like Ruby, Java, NodeJS, PHP, Perl, Python, and C#, among others. I personally prefer Python as itâs very easy to write code in python. A browser-dri
3 min read
How to scrape multiple pages using Selenium in Python?
As we know, selenium is a web-based automation tool that helps us to automate browsers. Selenium is an Open-Source testing tool which means we can easily download it from the internet and use it. With the help of Selenium, we can also scrap the data from the webpages. Here, In this article, we are g
4 min read
How to access popup login window in selenium using Python
Many websites use sign-in using social media to make the login process easy for users. In most cases, if the button is clicked then a new popup window is opened where the user has to enter their user credentials. Manually one can switch windows in a browser and enter the required credentials to log
3 min read
How to get current_url using Selenium in Python?
While doing work with selenium many URL get opened and redirected in order to keeping track of URL current_url method is used. The current_url method is used to retrieve the URL of the webpage the user is currently accessing. It gives the URL of the current webpage loaded by the driver in selenium.
2 min read
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
In this article, we are going to scrape LinkedIn using Selenium and Beautiful Soup libraries in Python. First of all, we need to install some libraries. Execute the following commands in the terminal. pip install selenium pip install beautifulsoup4In order to use selenium, we also need a web driver.
7 min read
How to click on an image using Selenium in Java?
Selenium, a popular tool for automating web application testing across browsers, often requires image interaction. In this article we will discuss how to clicking on image using Selenium in Java. PrerequisitesJava Development Kit (JDK) installed.Selenium WebDriver library added to your project.A sup
3 min read
How to select a drop-down menu value using Selenium in Python?
Prerequisite: Browser Automation Using Selenium Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we will be using Python
2 min read