How to start Selenium RemoteWebDriver or WebDriver without clearing cookies or cache?

旧城冷巷雨未停 提交于 2019-12-09 01:42:47

问题


Use case: Login with a username, navigated to a 2nd factor authentication page to do one of a number of things (i.e. answer a knowledge based question), and then navigated to a final page to enter a password. Close the browser and attempt to login again with the username. This time the 2nd factor authentication page is bypassed because the app recognizes the cookies and the user is prompted to enter their password directly.

Problem: I am using Selenium RemoteWebDriver to run these tests on a separate test machine and when I close the first browser and open a new instance of RemoteWebDriver it appears it starts by clearing cookies and cache and the 2nd factor authentication page comes up every time I attempt to login.

What I need: Help to figure out how to create a new instance of RemoteWebDriver without it automatically clearing any cookies or cache, so the 2nd factor authentication page will be bypassed. I need this for IE, Chrome, Firefox and Safari.

I don’t have any code that clears this explicitly, but I also don’t have anything that attempts to force it to not clear (if that’s even in existence.) I haven’t tried much of anything else because I have no idea what to try.

Versions: Selenium WebDriver: 2.45.0.0, Selenium Grid: 2.45.0

Thanks!


回答1:


To preserve cookies on Firefox; create a custom profile (see here for an example) and use it each time when starting new RemoteWebDriver instance. That way Firefox will reuse same profile with all the existing cookies across sessions. This however doesn't save cookies received during the test itself. See the alternative approach below for a solution.

A similar approach works for Chrome - link.

For Internet Explorer instead of a custom profile, ensureCleanSession capability needs to be set to false to prevent cleaning cookies on session start - link.

Alternative solution: Cookies can be also manipulated from within the test itself:

  1. Get all the cookies when test ends:

    ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies;

  2. Store them somewhere. How you do it depends on the automation setup, but usually simple serialization to disk should work just fine.

  3. De-serialize your cookies on test start and add them through the WebDriver:

    foreach (var cookie in cookies) driver.Manage().Cookies.AddCookie(cookie);



来源:https://stackoverflow.com/questions/29176528/how-to-start-selenium-remotewebdriver-or-webdriver-without-clearing-cookies-or-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!