用selenium(cookies)保存firefox会话

时间:2017-09-01 14:12:33

标签: c# selenium firefox cookies selenium-webdriver

我正在尝试从c#中的selenium驱动的firefox会话中保存cookie。我知道我可以通过序列化每个网站的每个cookie然后在网站上添加这些cookie来实现,但这不是最好的解决方案,因为: 1.我无法在加入网站之前设置cookie,所以我需要首先访问该网站然后添加cookie,但该网站已经设置了访问cookie,所以我需要删除它们并设置我的可能会导致网站问题。我宁愿让firefox和网站处理cookie。 2.我也需要担心过期的cookie 我已经尝试复制临时。 selenium创建的firefox配置文件。但是这似乎没有存储任何cookie,加载该配置文件也不起作用我得到错误:

OpenQA.Selenium.WebDriverException: 'Failed to set preferences: Unable to read profile preferences file'

但这不是唯一的问题,我没有在我复制的文件夹中看到任何cookie文件,只有扩展文件夹和user.js文件有一些偏好。这是我使用的代码:

        internal static void TestCookies()
    {
        //initialize driver and profile
        FirefoxProfile profile = new FirefoxProfile();
        FirefoxDriver driver = new FirefoxDriver(profile);
        profile.DeleteAfterUse = false;
        //set a cookie
        driver.Navigate().GoToUrl("http://winware.org/en/cookie-permanent.php");
        driver.FindElementByXPath("html/body/form/table/tbody/tr[4]/td[2]/input").SendKeys("TestValue1");
        driver.FindElementByXPath("html/body/form/table/tbody/tr[7]/td[2]/button").Click();
        Thread.Sleep(3000);
        Console.WriteLine(driver.Manage().Cookies.AllCookies.Count);
        profile.SetPreference("accessibility.typeaheadfind.flashBar", false);
        profile.WriteToDisk();
        Console.WriteLine(profile.ProfileDirectory);
        //move the temp directory to a different location
        Directory.Move(profile.ProfileDirectory, @"C:\Data\FirefoxProfiles\customprofile\");
        driver.Close();

        //test if cookie is still there
        profile = new FirefoxProfile(@"C:\Data\FirefoxProfiles\customprofile\"); //crashes here OpenQA.Selenium.WebDriverException: 'Failed to set preferences: Unable to read profile preferences file'
        driver = new FirefoxDriver(profile);

        driver.Navigate().GoToUrl("http://winware.org/en/cookie-permanent.php");
        Thread.Sleep(3000);
        Console.WriteLine(driver.Manage().Cookies.GetCookieNamed("PermanentCookie").Value);

    }

有没有人知道如何在不手动管理Cookie的情况下执行此操作?

0 个答案:

没有答案