![]() |
VOOZH | about |
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver.
Selenium WebDriver provides several methods to control the browser session, such as adding cookies, navigating back, switching tabs, and more. Managing cookies is often an important part of testing, especially when simulating scenarios like authentication where cookies may need to be manually added or removed. Selenium’s Python WebDriver offers methods to add, retrieve, and delete cookies, enabling testers to handle various practical use cases efficiently.
Selenium WebDriver provides various methods to manage cookies.
add_cookie method is used to add a cookie to your current session. This cookie can be used by website itself or by you.
Syntax -
add_cookie(cookie_dict)Example - Now one can use add_cookie method as a driver method as below -
driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’})Read More - add_cookie driver method.
get_cookie method is used to get a cookie with a specified name. It returns the cookie if found, None if not.
Syntax -
driver.get_cookie(name)Example - Now one can use get_cookie method as a driver method as below -
driver.get("https://www.geeksforgeeks.org///")
driver.get_cookie("foo")Read More - get_cookie driver method.
delete_cookie method is used to delete a cookie with a specified value.
Syntax -
driver.delete_cookie(name)Example - Now one can use delete_cookie method as a driver method as below -
driver.get("https://www.geeksforgeeks.org///")
driver.delete_cookie("foo")
Read More - delete_cookie driver method.
get_cookies method is used to get all cookies in current session. It returns a set of dictionaries, corresponding to cookies visible in the current session. Syntax -
driver.get_cookies()Example - Now one can use get_cookies method as a driver method as below -
driver.get("https://www.geeksforgeeks.org///")
driver.get_cookies()
Read More - get_cookies driver method.
We will demonstrate these methods by testing cookie management on https://www.geeksforgeeks.org//, We’ll add a cookie, retrieve it, verify its presence, and delete it.
Output:
We will demonstrate List all cookies, add a custom cookie, delete it, and confirm its removed or not.
Output:
Managing cookies in Selenium Python is straightforward with methods like add_cookie(), get_cookie(), delete_cookie(), and get_cookies(). These will let you simulate user sessions, test authentication, and verify personalization, making your tests faster and reliable.