Selenium Python Handle Cookies

Profile picture for user arilio666

To handle cookies in Selenium with Python, utilize selenium.webdriver module's built-in Cookie class.

Get Cookies

To retrieve all cookies in the current browser session, use the get_cookies() method.

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

driver.maximize_window()
driver.get('http://autopract.com/selenium/download.html')
cookies = driver.get_cookies()
for cookie in cookies:
   print(cookie)


Add Cookie

To create a new cookie, use the add_cookie() method and supply the required information, such as the name, value, domain, etc.

cookie = {'name': 'Luffy', 'value': 'Gear 5', 'domain': 'luffy.com'}
driver.add_cookie(cookie)

Delete Cookie

You can delete a specific cookie by invoking the delete_cookie() method and inputting the cookie's name.

cookie_name = 'Luffy'
driver.delete_cookie(cookie_name)

Delete All Cookies

The delete_all_cookies() method can be used to delete all cookies in the current browser session.

driver.delete_all_cookies()


Conclusion:

These methods enable you to interact with cookies in Selenium by retrieving, adding, and deleting cookies as needed in test automation scenarios.