Handling cookies in Selenium Python
In the previous articles on Selenium Python Tutorial, we have covered “How To Handle Web Tables in Selenium Python“. In this tutorial, we will learn Handling Cookies in Selenium Python.Â
We can handle cookies with the help of Selenium WebDriver. A cookie refers to some details about our application which is saved by the browser. A cookie monitors the user actions within an application and stores them in the form of key value pairs. For example, login information of a visitor of a website.
We can create, modify, or delete a cookie with Selenium WebDriver to verify the characteristics of an application having and not having a cookie. Let us discuss some of the methods to handle cookies:
add_cookie (n) – This method is capable of adding cookie. The cookie to be added is passed as a parameter[n] to the method.
Syntax:
driver.add_cookie ({ 'name' : 'f', 'value' : 'v'})
get_cookie (n) – This method is used to fetch a cookie with a name that is passed as a parameter[n] to the method.
Syntax:
driver.get_cookie ('f')
get_cookies () – This method without parameter is used to fetch all the cookies from the active session.
Syntax:
driver.get_cookies ()
delete_cookie (n) – This method is used to delete a cookie with a name that is passed as a parameter[n] to the method.
Syntax:
driver.delete_cookie ('f')
delete_all_cookies () – This method without parameter is used to delete all the cookies from the active session.
Syntax:
driver.delete_all_cookies ()
Code Implementation with cookie methods.
# import the webdriver from selenium import webdriver # import the Keys class from selenium.webdriver.common import keys driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe") # get method to launch the URL driver.get("https://www.softwaretestingmaterial.com/") # to add cookie driver.add_cookie ({'name' : 'f', 'value' : 'v'}) # to get cookie with name print (driver.get_cookie ('f')) # to get all the cookies print (driver.get_cookies ()) # to delete a cookie with name driver.delete_cookie ('f') # to delete all the cookies driver.delete_all_cookies () #to close the browser driver.close ()
In the next article, we will learn Working with excel in Selenium Python
Related posts:
- Selenium Python Tutorial
- Selenium Java Tutorial
- Selenium Interview Questions
- API Testing Tutorial
- Postman Tutorial