Selenium + Python · Lesson 32 of 43

0/43 done

Module 32: Cookies & Browser Storage

32. Cookie Injection & LocalStorage Management

15 minlesson

Your task

Implement set_auth_cookie(driver, cookie_name, cookie_value):

  1. driver.add_cookie({"name": cookie_name, "value": cookie_value})

Write it in the editor, then press Check answer (Ctrl + Enter).

python
# Add session cookie:
driver.add_cookie({"name": "session_id", "value": "token_123"})
driver.refresh()

# Clear cookies:
driver.delete_all_cookies()

# LocalStorage via execute_script:
driver.execute_script("localStorage.setItem('role', 'admin');")
role = driver.execute_script("return localStorage.getItem('role');")

Key Takeaways & Walkthrough Summary

Manipulating cookies allows you to bypass repeated UI logins and verify session persistence. In this lesson, you will master add_cookie, get_cookies, delete_all_cookies, and accessing localStorage via JavaScript in Python. Let's manage cookies!

Part of the Selenium + Python course (Selenium with Python). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why does add_cookie raise InvalidCookieDomainException?

You must navigate to the website domain first before attempting to add cookies for that domain.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Python
Skip