pythonselenium-webdriverselenium-chromedriver

Cookie cannot be added to website in selenium


from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import json
import time

service = Service(executable_path=f"chromedriver.exe", 
                  log_path=f"seleniumlog.txt")
selenium_options = Options()
selenium_options.add_argument("--disable-blink-features=AutomationControlled")
selenium_options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36")
selenium_options.add_experimental_option("excludeSwitches", ["enable-automation"])
selenium_options.add_experimental_option('useAutomationExtension', False)
chrome_driver = webdriver.Chrome(service=service, options=selenium_options)
chrome_driver.get("https://www.tiktok.com/login")

time.sleep(5)

cookie = {
    'domain': '.tiktok.com',
    'expiry': 1734578412,
    'httpOnly': True,
    'name': 'sessionid',
    'path': '/',
    'secure': True,
    'value': 'abc123'
}

# Step 2: Load cookies
with open("flamencocookies.json", "r") as f:
    cookies = json.load(f)

try:
    chrome_driver.add_cookie(cookie)
except Exception as e:
    print("Could not add cookie")

print(chrome_driver.get_cookies())

I'm just testing Selenium and chose TikTok.com to test it on. But in the above code, I'm unable to add the cookie to the browser session. The cookie format seems correct, and I'm not getting an exception, but it's also not added to the browser session. Does anyone know why? Could it be something to do with the switches I added to the browser?

Read selenium docs, everything seems correct


Solution

  • Your cookie won't add as it is expired. Update the time and it adds in fine:

    enter image description here

    I used this:

    cookie = {
        'domain': '.tiktok.com',
        'expiry': 1744835794, # <-- updated here
        'httpOnly': True,
        'name': 'sessionid',
        'path': '/',
        'secure': True,
        'value': 'abc123'
    }
    

    Cookies work on an epoch time. Which is number seconds since 1st Jan 1970.

    There are lots of handy converters available online.

    Your expiry time was set to: Thursday, 19 December 2024 03:20:12