How to set a cookie to a specific domain in selenium webdriver with Python?

PythonServer Side ProgrammingProgramming

We can set a cookie to a specific domain in Selenium webdriver with Python. A cookie is used to hold information sent by the browser. A key−value pair format is utilized and it is like a message provided to the browser by the server.

For cookie addition, the method add_cookie is used. The key and value are passed as parameters to the method. To get back all the cookies, get_cookies method is used. To get a specific cookie, the method get_cookie is used.

To delete cookies, the method delete_all_cookies is used.

Syntax

driver.add_cookie({"Automation": "QA"});
c= driver.get_cookies();
driver.get_cookie({"Automation");
driver.delete_all_cookies();

Example

from selenium import webdriver
#set geckodriver.exe path
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe")
driver.maximize_window()
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm")
#add cookie
c = {'name' : "Automation", 'value' : 'QA'}
driver.add_cookie(c);
#count total cookies
print(len(driver.get_cookies()))
#obtain cookie with name
print(driver.get_cookie("Automation"))
#delete cookies
driver.delete_all_cookies();
#check cookies after delete
d = driver.get_cookies()
print("Cookie count after all deletion")
print(len(d))
#close browser
driver.quit()

Output

raja
Published on 01-Feb-2021 11:53:26
Advertisements