[Python] How can I keep existing cookies when navigating between pages using Selenium...

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    I am writing a piece of code to log in to a webpage using credentials, wait until a booking comes open, and then refresh the page. However, after I successfully log in, as soon as I refresh the page, any cookies appear to be deleted and I'm logged out.

    Is there an option / argument I can add to keep the chrome webdriver from deleting cookies? Or is there another method I can use to ensure that I stay logged in when refreshing the page? Below is my code, any help is appreciated!

    from selenium.webdriver.common.keys import Keys
    from selenium import webdriver
    from selenium.common import NoAlertPresentException, TimeoutException
    from selenium.webdriver.common.by import By
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.support.ui import Select
    import time
    import pause
    from datetime import datetime
    from selenium.webdriver.chrome.options import Options


    options = Options()
    driver = webdriver.Chrome(options=options)
    driver.get("Website")
    time.sleep(2)
    # Hit log in button
    LogIn = driver.find_element(By.ID, "log-in-link")
    LogIn.click()
    # Enter email and password
    email = driver.find_element(By.ID, "email")
    email.send_keys("email")
    password = driver.find_element(By.ID, "sign-in-password")
    password.send_keys("password")

    SignIn = driver.find_element(By.CLASS_NAME, "sign-in-btn")
    SignIn.click()
    # Wait until 8 am exactly
    pause.until(datetime(2025, 2, 12, 8, minute=00, second=0, microsecond=0))
    # Refresh page at correct time
    driver.get(Website)

    # At this point the page refreshes and my code continues on, but I have been logged out due to the refresh

    Continue reading...

Compartilhe esta Página