Cookies handling

In Previous section we have discussed about handing Navigation like backward, forward, refresh the browsers in Selenium. Now we will discuss about the Cookies handling.

Objectives:

  • What is Cookies
  • How to Handle Cookies in Selenium
  • Practical Example

What is Cookies?

Cookies is nothing but a website data which will help you to define certain data whenever you are going to load the page like what kind of domain you have or what kind of language and localization etc.

For this learning we will use this https://www.reddit.com/ link.

How you will know a website has cookies or not. For this you need to do inspect element and navigate to Network and refresh the page. Here you can see the cookies listed.

How to handle Cookies in Selenium?

Handling cookies in Selenium is very easy to understand. For handling there are some methods are exist in Selenium. Let’s discuss them one by one.

driver.get_cookies():

This returns all cookies store in a dictionary.

from selenium import webdriver
from webdriver_manager.chromeimport ChromeDriverManager

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

driver.implicitly_wait(10)
driver.get('https://www.reddit.com/')
driver.maximize_window()

cookie_list = driver.get_cookies()

for cookies in cookie_list:
print(cookies)

You can see in console every cookies are printed. In this way you can simply print all the cookies of your website.

Adding Cookies:

Addition to printing cookies, you can add your custom cookie to your website. To achieve this you need to use add_cookie() method.

from selenium import webdriver
from webdriver_manager.chromeimport ChromeDriverManager

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

driver.implicitly_wait(10)
driver.get('https://www.reddit.com/')
driver.maximize_window()

cookie_list = driver.get_cookies()

for cookies in cookie_list:
print(cookies)

driver.add_cookie({"name" : "Pratik", "domain" : "reddit.com", "value": "Mishra"})


cookie_list = driver.get_cookies()

for cookies in cookie_list:
print(cookies)

Summary:

  • Cookies is nothing but a website data which will help you to define certain data whenever you are going to load the page like what kind of domain you have or what kind of language and localization etc.
  • driver.get_cookies():  returns all cookies store in a dictionary.
  • Addition to printing cookies, you can add your custom cookie to your website. To achieve this you need to use add_cookie() method.

Leave a Reply

Your email address will not be published. Required fields are marked *