A cookie is a message given to the web browser by a web server. This lets your web browser store information like login information, username, shopping cart and more. The website needs to remember this between different pages, cookies are sometimes used for this.

In selenium you can get and set cookies with the methods get_cookies() and add_cookie().

Related course:

selenium cookies

The selenium cookies code below gets all the cookies set by the site reddit.

1
2
3
4
5
6
7
8
9
10
11
# -*- coding: utf-8 -*-
from selenium import webdriver
import time

browser=webdriver.Firefox()
browser.get("https://reddit.com")
cookies = browser.get_cookies()
for cookie in cookies:
print(cookie)

browser.quit()

selenium cookies

selenium add delete cookies

The selenium code below gets cookies, then adds a new cookie, gets them again (to show) and finally deletes them.

1
2
3
4
5
6
7
8
9
10
11
12
# -*- coding: utf-8 -*-
from selenium import webdriver
import time

browser=webdriver.Firefox()
browser.get("https://reddit.com")
print(browser.get_cookies())
browser.add_cookie({"name":"python","domain":"reddit.com","value":"python"})
print(browser.get_cookies())
browser.delete_all_cookies()
print(browser.get_cookies())
browser.close()

selenium add delete cookies

If you are new to selenium, then I highly recommend this book.

Download examples