How to save and load cookies using Python Selenium WebDriver?

SeleniumAutomation TestingTesting Tools

We can save and load cookies with Selenium webdriver in Python. A cookie is an information saved by the browser about the application. A cookie is stored in a key value pair.

It is generally used to hold the credentials of users. It also stores information about the user actions on the browser within the cookie file. We can add, obtain and delete cookies of the browser.

Syntax

c = driver.get_cookies()
ck = { 'name': 'Selenium', 'value': 'Java'}
driver.add_cookie(ck)

Example

Code Implementation

from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/index.htm")
#get current cookies
c = driver.get_cookies()
print(c)
#count cookies with len method
print(len(c))
# load a new cookie
ck = { 'name': 'Selenium', 'value': 'Java'}
# save new cookie
driver.add_cookie(ck)
#get new cookies and total count after addition
ch = driver.get_cookies()
print(ch)
print(len(ch))
raja
Published on 28-Dec-2020 18:20:31
Advertisements