[Python] Cookie cannot be added to website in selenium

Discussão em 'Python' iniciado por Stack, Abril 6, 2025.

  1. Stack

    Stack Membro Participativo

    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())


    Im just testing selenium and chose TikTok.com to test it on. But in the above code, im unable to add the cookie to the browser session. The cookie format seems correct, im not getting an exception but its 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

    Continue reading...

Compartilhe esta Página