Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving chrome cookies Selenium

I am looking for a way to save a chrome session cookies to persist even after my program has been closed. I am assuming writing to a file would be a good way to go about doing this but I am at a loss as to how to accomplish this. My end goal is to save a login cookie so the user won't have to perform a login each time. Here is a bit of code:

Dim driver = New Chrome.ChromeDriver()
driver.Navigate.GoToUrl("URL")
'click stuff and login here
Dim _cookies = driver.Manage().Cookies.AllCookies
'write cookies to file or save somehow
like image 826
Zach Johnson Avatar asked Dec 02 '22 14:12

Zach Johnson


1 Answers

You need to run Chrome under the required user profile. By default, the Selenium web driver will create a temporary profile. If you give it a user profile, the profile will persist and if Chrome is not set to delete cookies, any logins etc. that would normally create a cookie for a user will be created.

See Selenium chromedriver site for details:

Use custom profile (also called user data directory)
By default, ChromeDriver will create a new temporary profile for each session. At times you may want to set special preferences or just use a custom profile altogether. If the former, you can use the 'chrome.prefs' capability (described later below) to specify preferences that will be applied after Chrome starts. If the latter, you can use the user-data-dir Chrome command-line switch to tell Chrome which profile to use:

ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=/path/to/your/custom/profile");

You can create your own custom profile by just running Chrome (on the command-line or through ChromeDriver) with the user-data-dir switch set to some new directory. If the path doesn't exist, Chrome will create a new profile in the specified location. You can then modify the profile settings as desired, and ChromeDriver can use the profile in the future. Open chrome://version in the browser to see what profile Chrome is using.
like image 109
Alan Avatar answered Dec 22 '22 02:12

Alan