Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#/ASP.NET Selenium WebDriver - Re-using Cookies

I want to:

  • Login to a website
  • Save Cookies
  • Give user a choice to do A, B or C
  • A,B and C all require being logged in.
  • Each will open a FirefoxDriver and do their own thing

What i want to do, is login ONCE, save the cookies from that, and add them to any other FirefoxDriver i want to open.

Right now I'm trying to save the cookies in

public ReadOnlyCollection<Cookie> Cookies { get; set; }

which is the result of

WebDriver.Manage().Cookies.AllCookies;

Assuming login worked and cookies were saving in the above, I have this:

        WebDriver = new FirefoxDriver();
        WebDriver.Navigate().GoToUrl("http://www.example.com");

        if (cookies != null)
        {
            var s = WebDriver.Manage().Cookies;  //Logged out cookies
            WebDriver.Manage().Cookies.DeleteAllCookies(); //Delete all of them
            var sd = WebDriver.Manage().Cookies; //Make sure theyre deleted
            foreach (var cookie in cookies)
            {
                WebDriver.Manage().Cookies.AddCookie(cookie);
            }
            var ss = WebDriver.Manage().Cookies; 
            WebDriver.Navigate().GoToUrl("http://example.com/requiresloginpage");
        }

The problem is, howevering over "ss" in this case, gives this exception error

AllCookies = 'ss.AllCookies' threw an exception of type
'OpenQA.Selenium.WebDriverException'
base {System.Exception} = {"Unexpected problem getting cookies"}
InnerException = {"Cookie name cannot be null or empty string\r\nParameter name: name"}

I'm passing 8 cookies (total number when youre logged in) - and all of them seem set and ok. Not sure what I'm doing wrong

like image 968
Alan Ciantar Avatar asked Jun 27 '13 14:06

Alan Ciantar


1 Answers

In order to save cookies, you should tell selenium to use a specified profile. For some reason I can't get it to use my normal Chrome profile, but this solution will allow you to log in one time, and afterward, selenium will remember cookies.

ChromeOptions options = new ChromeOptions();
options.AddArguments(@"user-data-dir=C:\Users\YOU\AppData\Local\Google\Chrome\User Data\NAMEYOUCHOOSE");
//specify location for profile creation/ access
ChromeDriver driver = new ChromeDriver(options);

Simply put, this code creates a save location for a profile, which does include cookies. using this code, it is not necessary to write code that saves or loads cookies, Chrome will handle that.

Please note that the location where chrome saves your profiles may be different than mine, and I have only successfully used a directory that leads to the same location as my regular Chrome profile. This profile exists in the form of a folder, not a file.

like image 155
SJ10 Avatar answered Sep 17 '22 17:09

SJ10