How to work with cookies in Selenium with python?

Selenium Web DriverAutomation TestingSoftware Testing

We can work with cookies in Selenium with the help of numerous methods which control the browser or its sessions. We can easily add or delete a cookie. A cookie implementation is essential for ensuring proper authentication of websites.

The methods to work with cookie are listed below −

  • add_cookie(args)

    This method adds a cookie to the present session. The arguments consist of the names of the cookies that we want to add.

Syntax

driver.add_cookie({'id' : 'val' : 'session'})
  • get_cookie(args)

    This method gets a cookie of a specific name. The argument consists of the name of the cookie that we want to retrieve.

Syntax

driver.get_cookie("name")
  • delete_cookie(args)

    This method deletes a cookie with a specific name. The argument consists of the names of the cookies that we want to delete.

Syntax

driver.delete_cookie("session")
  • delete_all_cookies()

    This method deletes all cookies in the present session. It has no arguments.

Syntax

driver.delete_all_cookies()
  • get_cookies()

    This method returns all the cookies in the present session in the form of dictionaries.

Syntax

driver.get_cookies()

Example

Coding Implementation on addition and deletion of cookies.

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
#to refresh the browser
driver.refresh()
#to add cookies of particular names
driver.add_cookie({'id' : 'val': 'session'})
#to get a specific cookie
print(driver.get_cookie("id"))
#to get all cookies of the session
print(driver.get_cookies())
#to delete a particular cookie
driver.delete_cookie("val")
#to delete all cookies in present session
driver.delete_all_cookies()
raja
Published on 29-Jul-2020 13:08:52
Advertisements