Working with Cookies in Python Selenium

In this Python Selenium article we want to learn about Working with Cookies in Python Selenium, In web development and testing, cookies play an important role in storing and retrieving information about a user browsing activities. Python Selenium is a powerful tool for browser automation, and it offers excellent support for handling cookies.



To work the examples of this tutorial you need some requirements, first you should have installed Python in your system, then we need to install Python Selenium and you can use pip for that like this.



First of all we need to import our required module from Python Selenium.



After that we need to launch a browser instance. In this example, we are going to use Google Chrome. instantiate a webdriver.Chrome object, which represents the browser window.



To demonstrate cookie handling, let’s open and search for a term. we are going to use the get() method of the webdriver object to navigate to the desired URL.



To retrieve the cookies from the current browser session, we can use the get_cookies() method. it returns a list of dictionaries, where each dictionary represents a cookie.



For adding a new cookie, we use add_cookie() method, which accepts a dictionary containing the cookie details. In this example, let’s add a custom cookie with the name example_cookie and value 12345.



After adding the new cookie, we can verify its presence by retrieving the cookies again and checking if the added cookie is present.



If you want to remove a specific cookie, you can use delete_cookie() method and provide the cookie name.



After that you have finished working with the browser, remember to close it using the close() method.




This is the complete code for this article




Run the code and this will be the result

Working with Cookies in Python Selenium
Working with Cookies in Python Selenium




Learn More on Python Selenium

Leave a Comment