9

I am using Selenium to Log In to an account. After Logging In I would like to save the session and access it again the next time I run the python script so I don't have to Log In again. Basically I want to chrome driver to work like the real google chrome where all the cookies/sessions are saved. This way I don't have to login to the website on every run.

browser.get("https://www.website.com")
browser.find_element_by_xpath("//*[@id='identifierId']").send_keys(email)
browser.find_element_by_xpath("//*[@id='identifierNext']").click()
time.sleep(3)
browser.find_element_by_xpath("//*[@id='password']/div[1]/div/div[1]/input").send_keys(password)
browser.find_element_by_xpath("//*[@id='passwordNext']").click()
time.sleep(5)
Deepak Rai
  • 2,163
  • 3
  • 21
  • 36
MA19112001
  • 164
  • 2
  • 3
  • 16
  • Does this answer your question? [Python: use cookie to login with Selenium](https://stackoverflow.com/questions/45417335/python-use-cookie-to-login-with-selenium) – Celius Stingher Aug 13 '20 at 16:40
  • 1
    You can get chrome browser default profile path when it is launched with selenium and you can set this a `user-data-dir` for next launch which will load all cookies. To get chrome cookie file path https://sqa.stackexchange.com/questions/45192/how-to-get-the-chrome-browser-cookie-file-path-when-it-is-launched-from-selenium/45196#45196 – Mohamed Sulaimaan Sheriff Aug 13 '20 at 17:59

4 Answers4

11

As @MohamedSulaimaanSheriff already suggested, you can open Chrome with your personal chrome profile in selenium. To do that, this code will work:

options = webdriver.ChromeOptions()
options.add_argument(r'--user-data-dir=C:\Users\YourUser\AppData\Local\Google\Chrome\User Data\')
PATH = "/Users/yourPath/Desktop/chromedriver"
driver = webdriver.Chrome(PATH, options=options)

Of course you can setup extra User Data for your script by creating a new User Data Directory and replace the path. Make sure that you copy your existing User Data to ensure you're not provoking any errors. Afterwards you could reset them in Chrome itself.

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
benicamera
  • 750
  • 1
  • 7
  • 24
2

This is the solution I used:

# I am giving myself enough time to manually login to the website and then printing the cookie
time.sleep(60)
print(driver.get_cookies())

# Than I am using add_cookie() to add the cookie/s that I got from get_cookies()
driver.add_cookie({'domain': ''})

This may not be the best way to implement it but it's doing what I was looking for

MA19112001
  • 164
  • 2
  • 3
  • 16
  • Save the cookies in a separate file like pickle or h5 is much better option than hardcoding the data. – Muhammad Afzaal Apr 20 '22 at 19:22
  • @MuhammadAfzaal Muhammad doyou know how to save it and later how to load it? – RodParedes Jun 25 '22 at 19:11
  • @RodParedes pickel and h5 is a file format just like txt file. You have to save the response cookies in pickle or h5 file using the dump method and read the file when you need the cookies again. The method is just simple as writing a text file. – Muhammad Afzaal Jun 30 '22 at 14:55
  • @RodParedes pickle file is used to store fewer storage objects on the other hand h5 is used for much bigger objects. – Muhammad Afzaal Jun 30 '22 at 14:59
1

First login to the website and print your cookie with this:

print(driver.get_cookies())

Then try:

driver.get("<website>")
driver.add_cookie({'domain':''})
Anurag A S
  • 725
  • 10
  • 23
shakib
  • 61
  • 1
  • 6
0

THIS IS C# CODE SOLUTION

CREDITS: Can't save the session of Whatsapp web with Selenium c#


  1. First choose a FOLDER where to save the webdriver session.

  1. Then if folder not exist create a new Chrome Driver Session and save it using this function:

    public static IWebDriver OpenNewChrome(string FolderPathToStoreSession)
    {
        ChromeOptions options = null;
        ChromeDriver driver = null;
        try
        {
            //chrome process id
            int ProcessId = -1;
            //time to wait until open chrome
            //var TimeToWait = TimeSpan.FromMinutes(TimeToWaitInMinutes);
            ChromeDriverService cService = 
            ChromeDriverService.CreateDefaultService();
            //hide dos screen
            cService.HideCommandPromptWindow = true;
            options = new ChromeOptions();
            //options.AddArguments("chrome.switches", "--disable-extensions");

            //session file directory
            options.AddArgument("--user-data-dir=" + FolderPathToStoreSession);
            driver = new ChromeDriver(cService, options);

            //set process id of chrome
            ProcessId = cService.ProcessId;

            return driver;
        }
        catch (Exception ex)
        {
            if (driver != null)
            {
                driver.Close();
                driver.Quit();
                driver.Dispose();
            }
            driver = null;
            throw ex;
        }
    }
  1. If the folder exist open again the previous Chrome session using this function:

public static IWebDriver OpenOldChrome(string FolderPathToStoreSession)
    {
        ChromeOptions options = null;
        ChromeDriver driver = null;
        try
        {
            //chrome process id
            int ProcessId = -1;
            //time to wait until open chrome
            //var TimeToWait = TimeSpan.FromMinutes(TimeToWaitInMinutes);
            ChromeDriverService cService = ChromeDriverService.CreateDefaultService();

            //hide dos screen
            cService.HideCommandPromptWindow = true;

            options = new ChromeOptions();

            //session file directory
            options.AddArgument("--user-data-dir=" + FolderPathToStoreSession);
            //options.AddArgument("--no-sandbox");

            //options.AddArgument("--headless=new");

            //Add EditThisCookie Extension
            //options.AddArguments("chrome.switches", "--disable-extensions");
 //options.AddExtensions("\\ChromeExtensions\\editthiscookie.crx");

            driver = new ChromeDriver(cService, options);

            //set process id of chrome
            ProcessId = cService.ProcessId;

            return driver;
        }
        catch (Exception ex)
        {
            if (driver != null)
            {
                driver.Close();
                driver.Quit();
                driver.Dispose();
            }
            driver = null;
            throw ex;
        }
    }

PS. If you don't want Chrome Extensions to be installed or saved uncomment this option:

options.AddArguments("chrome.switches", "--disable-extensions");
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
gabrielepetteno
  • 89
  • 1
  • 11