How to Handle Cookies in Selenium WebDriver

QASource Engineering Team | February 29, 2024

How to Handle Cookies in Selenium WebDriver

Handling cookies with Selenium WebDriver is crucial for managing session data and ensuring smooth web automation. Here’s a comprehensive guide on effectively handling cookies using Selenium WebDriver.

  1. Retrieving Cookies

    To retrieve cookies in Selenium WebDriver, you can use the get_cookies() method. This method returns a set of cookies associated with the current session.

    #Python code to retrieve cookies
    cookies = driver.get_cookies()

  2. Adding Cookies

    To add cookies in Selenium WebDriver, use the add_cookie() method. This method accepts a dictionary object representing the cookie parameters.

    #Python code to add a cookie
    cookie = {'name': 'example_cookie', 'value': 'example_value'}
    driver.add_cookie(cookie)

  3. Deleting Cookies

    Deleting cookies in Selenium WebDriver can be done using the delete_cookie() or delete_all_cookies() methods. The former deletes a specific cookie by name, while the latter clears all cookies from the current session.

    #Python code to delete a specific cookie
    driver.delete_cookie('example_cookie')

    Python code to delete all cookies
    driver.delete_all_cookies()

  4. Handling Specific Cookies

    You can handle specific cookies by retrieving them, modifying their values, and adding them back to the session.

    #Python code to modify and add a specific cookie
    specific_cookie = driver.get_cookie('specific_cookie')
    specific_cookie['value'] = 'modified_value'
    driver.add_cookie(specific_cookie)

  5. Managing Cookie Expiry

    You can manage cookie expiration by setting the expiry attribute in the cookie dictionary.

    # Python code to set a cookie expiry
    import datetime
    expiry_date = datetime.datetime.now() + datetime.timedelta(days=30)
    cookie['expiry'] = int(expiry_date.timestamp())
    driver.add_cookie(cookie)

 

Handling Cookies in Selenium WebDriver with an Example

Suppose we have a scenario where we need to automate the login process for a website and then handle the authentication token stored in a cookie for subsequent requests. Here's how we can achieve this using Selenium WebDriver in Python:

#Initialize the WebDriver
driver = webdriver.Chrome()

#Navigate to the login page
driver.get("https://example.com/login")

#Perform login (fill in username and password)
username_input = driver.find_element_by_id("username")
password_input = driver.find_element_by_id("password")
login_button = driver.find_element_by_id("login-button")
username_input.send_keys("your_username")
password_input.send_keys("your_password")
login_button.click()

# After successful login, retrieve the authentication token from the cookie
auth_cookie = driver.get_cookie("auth_token")

if auth_cookie:
# If the authentication token cookie exists, extract the token value
auth_token = auth_cookie["value"]
print("Authentication token:", auth_token)

#Now, you can use this authentication token for subsequent requests #For example, sending authenticated requests to an API

#Example: Sending an authenticated request to an API using the requests library
import requests
headers = {"Authorization": "Bearer " + auth_token}
response = requests.get("https://api.example.com/data", headers=headers)
if response.status_code == 200:
print("API Response:", response.json())
else:
print("Failed to fetch data from API")
else:
print("Authentication token cookie not found")

# Close the WebDriver session
driver.quit()

The following example illustrates:

  1. We navigated to the login page of the website.
  2. After entering the username and password and clicking the login button, we retrieve the authentication token stored in the cookie.
  3. If the authentication token cookie exists, we extract the token value and demonstrate how it can be used for subsequent authenticated requests. Here, we simulate requesting an API using the authentication token.
  4. Finally, we close the WebDriver session.

Selenium WebDriver can handle cookies, specifically extracting and utilizing cookie data (in this case, an authentication token) for further actions in an automated testing or web scraping scenario.

By mastering cookie handling in Selenium WebDriver with these techniques and examples, you can significantly enhance the robustness and efficiency of your web automation scripts.

Disclaimer

This publication is for informational purposes only, and nothing contained in it should be considered legal advice. We expressly disclaim any warranty or responsibility for damages arising out of this information and encourage you to consult with legal counsel regarding your specific needs. We do not undertake any duty to update previously posted materials.

Post a Comment