Selenium Python Handle Cookies

Profile picture for user arilio666
Submitted by arilio666 on

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 import ChromeDriverManager
from import By
from import Service

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

cookies = driver.get_cookies()
for cookie in cookies:

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': ''}

Delete Cookie

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

cookie_name = 'Luffy'

Delete All Cookies

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



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