3

This is what I want to perform using WebDriver.

  1. Login to the site with selected check box keep user logged in.
  2. Close the browser.
  3. Go to the site again and make sure that user is logged in.

The problem is when I close the driver and reopen it, I am not signed in.

My code looks like this-

   WebDriver myD = null;
    myD = new FirefoxDriver();
    String URL = "https://www.eurostylelighting.com/protected/account/signin?ReturnUrl=%2f";
    myD.navigate().to(URL);
    myD.findElement(By.cssSelector("input#txtEmailorRewards")).sendKeys("abc@yahoo.com");           
    myD.findElement(By.cssSelector("input#txtPassword")).sendKeys("abc");
    myD.findElement(By.xpath(".//*[@id='accountSignIn']/dl[4]/dd/label/span")).click();
Set<Cookie> cookies = myD.manage().getCookies();
    myD.close();
    myD= new FirefoxDriver();
    myD.navigate().to(URL);
for(Cookie getCookie:cookies)
            myD.manage().addCookie(getCookie);
For Testing
  • 281
  • 2
  • 5
  • 19
  • 1
    Possibly reuse the cookies. See [this](http://stackoverflow.com/questions/30292025/selenium-trying-to-log-in-with-cookies-can-only-set-cookies-for-current-doma) – Saifur May 26 '15 at 14:13
  • Thanks Saifur. I edited my code but not I get Exception - you may only set cookies to the current domain. – For Testing May 26 '15 at 15:05
  • why not executing the for before the navigate? You're navigating BEFORE adding the cookies again, it seems pretty obvios that you won't be signed in. – DGoiko May 10 '20 at 19:32

3 Answers3

5
  1. You can create firefox/another browser profile and use it. All cookies in this case will be saved inside of this profile.

  2. you can add hardcoded cookies after browser open. But in this case they will be "static".(the same on every session)

  3. If you need to only to do check of login/logout you can save cookies manually to some variables, remove cookies from webdriver, refresh page, add cookies back.

  4. Most easy way will be to use serialization. (create own class for cookies and save/load it to/from hdd) This is the best choice!

  5. you can write code to save cookies to xml file before browser close and to load on driver start. This is example of realization in C# of such functionality using Linq:

.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace Ifrit
{
    public class CookiesManager
    {
        XDocument xmlDoc;
        string xml_path;

        public CookiesManager()
        {
            xml_path = ParamsLib.BrwsrOptions.BrowserCookiesFile;

            xmlDoc = new XDocument();

            if (File.Exists(xml_path))
            {
                xmlDoc = XDocument.Load(xml_path);
            }
            else
            {
                var xmlBodyNode = new XElement("body","");
                var xmlCList = new XElement("cookies_list","");

                xmlBodyNode.Add(xmlCList);

                xmlBodyNode.Save(xml_path);
                xmlDoc = XDocument.Load(xml_path);
            }
        }

        public List<MyCookie> GetCookiesForUser(string user_name)
        {
            List<MyCookie> cookiesList = new List<MyCookie>();
            try
            {
                cookiesList = (from e in xmlDoc.Root.Elements("cookies_list")
                               let cookie = e.Element("cookie")
                               where (string)cookie.Attribute("user_name") == user_name
                               select new MyCookie
                               {
                                   name = (string)cookie.Attribute("c_name"),
                                   value = (string)cookie.Attribute("c_value"),
                                   domain = (string)cookie.Attribute("c_domain"),
                                   path = (string)cookie.Attribute("c_path"),
                                   expiries = (string)cookie.Attribute("c_expiries"),
                                   secure = (string)cookie.Attribute("c_secure"),
                               }).ToList();
            }
            catch 
            { }

            return cookiesList;
        }

        public void AddCookiesForUser(string username, string cookieName, string cookieValue, string domainName, string path, string expiries, string secure)
        {
            var xmlNode =  new XElement("cookie",   new XAttribute("user_name", username),
                                new XAttribute("c_name", cookieName),
                                new XAttribute("c_value", cookieValue),
                                new XAttribute("c_domain", domainName),
                                new XAttribute("c_path", path),
                                new XAttribute("c_expiries", expiries),
                                new XAttribute("c_secure", secure)
            );

            xmlDoc.Element("body").Element("cookies_list").Add(xmlNode);
        }

        public void Save()
        {
            xmlDoc.Save(xml_path);
        }

        public void removeCookieForUser(string username)
        {
            try
            {
                xmlDoc.Element("body").Element("cookies_list").Descendants("cookie")
                                   .Where(x => (string)x.Attribute("user_name") == username)
                                   .Remove();
            }
            catch 
            { 
            }
        }


        public class MyCookie
        {
            public string name { get; set; }
            public string value { get; set; }
            public string domain { get; set; }
            public string path { get; set; }
            public string expiries { get; set; }
            public string secure { get; set; }
        }

    }
}

In this case there is possible to save all cookies in XML and load from MyCookie to Cookie by additional function-wrapper and load cookies when its needed.

By the way this is example of cookies XML file:

<?xml version="1.0" encoding="utf-8"?>
<body>
  <cookies_list>
    <cookie user_name="SomeName" c_name="6a64d0796e530a04069945d05c4074ca" c_value="yes" c_domain="www.marathonsportsbook.com" c_path="/" c_expiries="17.05.2057 15:41:44" c_secure="True" />
    <cookie user_name="SomeName" c_name="2b132c80be5271bcd9a0dddcc2f12c18" c_value="yes" c_domain="www.marathonsportsbook.com" c_path="/" c_expiries="17.05.2057 15:41:44" c_secure="True" />
    <cookie user_name="SomeName" c_name="PUNTER_KEY" c_value="A81B639C8F69931DAAD24DE4A8972632" c_domain=".marathonsportsbook.com" c_path="/" c_expiries="27.05.2016 15:41:44" c_secure="True" />
    <cookie user_name="SomeName" c_name="JSESSIONID" c_value="web2~F8D01B04BDE8C9702A1795521E06B218" c_domain="www.marathonsportsbook.com" c_path="/" c_expiries="28.05.2015 15:46:16" c_secure="True" />
    <cookie user_name="SomeName" c_name="afterLoginRedirectPath" c_value="&quot;https://www.marathonsportsbook.com/en/&quot;" c_domain="www.marathonsportsbook.com" c_path="/" c_expiries="28.05.2015 15:46:16" c_secure="True" />
  </cookies_list>
</body>

user_name="SomeName" -- is cookie profile name

Andrew_STOP_RU_WAR_IN_UA
  • 9,318
  • 5
  • 65
  • 101
3

Yes, you cannot add the cookies that do not belong the domain you are using. As I have mentioned in other answer, do a filtering depending on the domain and see if the cookies belong to the test domain. You can do the following:

WebDriver myD = null;
myD = new FirefoxDriver();
String URL = "https://www.eurostylelighting.com/protected/account/signin?ReturnUrl=%2f";
myD.navigate().to(URL);
myD.findElement(By.cssSelector("input#txtEmailorRewards")).sendKeys("abc@yahoo.com");           
myD.findElement(By.cssSelector("input#txtPassword")).sendKeys("abc");
myD.findElement(By.xpath(".//*[@id='accountSignIn']/dl[4]/dd/label/span")).click();
Set<Cookie> cookies = myD.manage().getCookies();
myD.close();
myD= new FirefoxDriver();
myD.navigate().to(URL);
for(Cookie getCookie:cookies){
    if(getCookie.domain.equals("Your domain")){
        myD.manage().addCookie(getCookie);
    }
}

Note: you cannot add cookies to localhost. Use IP or something else if that's the case

Saifur
  • 16,081
  • 6
  • 49
  • 73
0

I've copypasted Andrew answer, but GetCookiesForUser method returns only first cookie from his example

<cookie user_name="SomeName" c_name="6a64d0796e530a04069945d05c4074ca"     c_value="yes" c_domain="www.marathonsportsbook.com" c_path="/" c_expiries="17.05.2057 15:41:44" c_secure="True" />

local variable cookiesList holds only one element.

I think linq query has to be changed to

from e in xmlDoc.Root.Elements("cookies_list")
                              where (string)e.Element("cookie").Attribute("user_name") == user_name
                              from c in e.Elements("cookie")
                              select new MyCookie

The main idea is to iterate not through cookies of several user_names, but through separate cookies of one user_name