Selenium is a Python automation module used to automate and test web applications. In this answer, we'll learn to handle cookies in Selenium using Python.
Cookies are files that contain small pieces of data sent by the server to the web browser. We can store, retrieve, delete, and list cookies using the below methods:
add_cookie()
: We can add a cookie using this method.
get_cookies()
: It is used to list all cookies.
get_cookie()
: It is used to get only one cookie based on its name.
delete_cookie()
: It is used to delete a cookie based on its name.
delete_all_cookies()
: It is used to delete all the cookies.
Let’s look at the example below:
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service import time options = Options() options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') prefs = {"download.default_directory": "."} options.add_experimental_option("prefs", prefs) #get instance of web driver driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) #provide website url here driver.get("https://omayo.blogspot.com/") # add cookies driver.add_cookie ({ 'name' : 'firstname', 'value' : 'James'}) driver.add_cookie ({ 'name' : 'lastname', 'value' : 'xyz'}) print("---List of cookies after adding all cookies---") # get all cookies print(driver.get_cookies()) print("---Display cookie which has name as firstname---") # get cookie with its name print(driver.get_cookie('firstname')) # delete cookie driver.delete_cookie('lastname') print("---List of cookies after deleting one cookie---") print(driver.get_cookies()) #delete all cookies driver.delete_all_cookies() print("---List of cookies after deleting all cookies---") print(driver.get_cookies()) time.sleep(10)
Line 14: We create an instance of a web driver and assign it to a variable driver
.
Line 17: We open the web page using the get()
method.
Lines 20–21: We add cookies to the current webpage using the add_cookie()
method.
Line 26: We list all the cookies present using the get_cookies()
method. It will return a list of cookies as a list of dictionaries.
Line 31: We can get information about a cookie based on its name using the get_cookie()
method.
Line 34: We delete a cookie based on its name lastname
using the delete_cookie()
method.
Line 40: We delete all cookies using the delete_all_cookies()
method.
Free Resources