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
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read