How to save the browser sessions in Selenium?
Asked Answered
T

4

10

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)
Tuckie answered 13/8, 2020 at 16:31 Comment(2)
Does this answer your question? Python: use cookie to login with SeleniumAngst
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 sqa.stackexchange.com/questions/45192/…Janerich
T
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

Tuckie answered 16/8, 2020 at 18:28 Comment(5)
Save the cookies in a separate file like pickle or h5 is much better option than hardcoding the data.Tova
@MuhammadAfzaal Muhammad doyou know how to save it and later how to load it?Bonni
@Bonni 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.Tova
@Bonni pickle file is used to store fewer storage objects on the other hand h5 is used for much bigger objects.Tova
Thank you for the solution. The issue arises from a domain change affecting cookie behavior. However, maintaining the same domain triggers an InvalidCookieDomainException, especially with domains prefixed with a dot, such as '.google.com'."Prepossession
D
13

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.

Dickie answered 15/8, 2020 at 17:54 Comment(2)
It seems it stopped working in Chrome v. 102. Chrome is started with all sessions cleared.Cello
@VladimirObrizan On v116 works well, may you are giving path messed with spaces or quotes (I've had the same problem)Spotweld
T
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

Tuckie answered 16/8, 2020 at 18:28 Comment(5)
Save the cookies in a separate file like pickle or h5 is much better option than hardcoding the data.Tova
@MuhammadAfzaal Muhammad doyou know how to save it and later how to load it?Bonni
@Bonni 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.Tova
@Bonni pickle file is used to store fewer storage objects on the other hand h5 is used for much bigger objects.Tova
Thank you for the solution. The issue arises from a domain change affecting cookie behavior. However, maintaining the same domain triggers an InvalidCookieDomainException, especially with domains prefixed with a dot, such as '.google.com'."Prepossession
M
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':''})
Metatarsus answered 24/6, 2022 at 7:55 Comment(0)
C
1

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");
Chace answered 28/7, 2023 at 0:19 Comment(2)
Thanks! (Looks like OpenNewChrome == OpenOldChrome when ignoring comments)Tinsley
@Tinsley Yes, exacly they are the same! It depends only on the FolderPathToStoreSession. If there is a session on FolderPathToStoreSession (open the existing session) else (open new session)Chace

© 2022 - 2024 — McMap. All rights reserved.