Cookies handling using Selenium WebDriver

October 7, 2016

In this tutorial, we will learn how to handle cookies stored by a browser using Selenium WebDriver. Before starting with handling cookies, let us first understand cookies.

What is a cookie?

Cookies are small text files, stored by a browser in its directory. These files are generated when a web page is visited. It helps you resume your browsing from the point you left off. helps you remember your registered login and other information which you voluntarily provide while visiting a Webpage.

Cookies stores information in a key-value pair. This information is sent to the website next time you visit the same page.

How to check cookies on a web page in a browser:

In Firebug, there is a Cookies tab, refer below screenshot for your reference:

cookie handling

Attributes in Cookies:

  • Name – This attribute is the name of the cookie. Cookies are stored in a key-value pair, this attribute can be considered as key.
  • Value – This is the value of name.
  • Domain – Domain tells on which domain a particular cookie is valid.
  • Raw Size – This attribute tells the size of the file of cookie
  • Path – Path where is this cookie is saved.
  • Expires – This attribute tells the expiry date of a cookie
  • HttpOnly – If it’s only HTTP cookie.

Cookies Handling using Selenium WebDriver:

Selenium WebDriver provides methods to add, delete, get a cookie etc to handle cookies.

  • Add a particular Cookie – To add a specific cookie into cookies in a browsing session.

cookie output

  • Delete All cookies – To delete all the cookies before navigating to a particular web page.
  • Delete cookies with Name – To delete a particular cookie with some name.
  • Delete Cookie – To delete a specific cookie, before browsing to a web page.
  • Get All  Cookies – To get all the cookies from a particular browsing session.

In first two examples, we have called a method to get all the cookies. The Method used is “getCookies()”, this method returns a Set of cookies. Using enhanced for-loop we can iterate over all the cookies and then can get all the attribute. See the example below:

  • Get Cookie with a specific name – To get a specific cookie.

PS: For any questions queries or comment feel free to write us at saurabh@qatechhub.com or support@qatechhub.com. Happy Learning 🙂

Saurabh

About the Author

Saurabh

Follow Saurabh:

Leave a Comment: