Last modified: Jan 02, 2024 By Alexander Williams
Python Selenium: Get Cookies - Examples
Example 1: Get All Cookies
from selenium import webdriver
# Create a Chrome driver
driver = webdriver.Chrome()
# Navigate to a webpage
driver.get('https://example.com')
# Get all cookies associated with the current domain
all_cookies = driver.get_cookies()
# Print the obtained cookies
print(all_cookies)
Output:
# Output will be a list of dictionaries, each representing a cookie.
Example 2: Get Specific Cookie
# Continue from the previous example
# Get a specific cookie by name
specific_cookie = driver.get_cookie('example_cookie_name')
# Print the obtained specific cookie
print(specific_cookie)
Output:
# Output will be a dictionary representing the specific cookie.
Example 3: Analyze Cookie Attributes
# Continue from the first example
# Analyze attributes of each cookie
for cookie in all_cookies:
name = cookie['name']
value = cookie['value']
domain = cookie['domain']
secure = cookie['secure']
# Perform actions based on cookie attributes
# Example: Print cookie information
print(f'Name: {name}, Value: {value}, Domain: {domain}, Secure: {secure}')
Output:
# Output will be information about each cookie.