Selenium - Switching between Two WebDrivers

Hi All, 

From last two days I was facing with a problem that I need to switch between two WebDrivers. Actually the issue was, while switching between the WebDrivers the session get expired.

Finally found a solution for that and want to share with you.

Problem was:

First I need to run a WebDriver and execute some scripts, then need to run a HtmlUnitDriver and execute another set of actions again want to switch back to previously opened WebDriver  and execute final set of actions.

To solve this, I have tried the scripts like:

HtmlUnitDriver HTMLDriver = new HtmlUnitDriver();

WebDriver driver= ChromeDriver();

<Step1 : Actions with driver>

<Step2 : Actions with HTMLDriver >

driver=HTMLDriver;

<Step3 : Actions with driver in continuation of Step2>

driver=HTMLDriver; --> This will copy the HtmlUnitDriver to WebDriver, but the problem was with the Session, to maintain the session we need to copy the cookies of the HtmlUnitDriver to WebDriver

Then tried with following code for copying the session :

for (Cookie c : HTMLDriver.manage().getCookies()) {
driver.manage().addCookie(c);
}

Yes, me also thought that this will solve the issue, but still getting "Session Expired" message. What we will do in this case, Nothing else, just logged the cookies of both the Drivers and observed that the "driver" contains a cookie repeated two times with different values.

How we will solve this ? Yah ! right, clear all the cookies of "driver" before copying cookies from HTMLDriver.

and the final code looks like this:

HtmlUnitDriver HTMLDriver = new HtmlUnitDriver();

WebDriver driver= ChromeDriver();

<Step1 : Actions with driver>

<Step2 : Actions with HTMLDriver >

driver.manage().deleteAllCookies();

for (Cookie c : HTMLDriver.manage().getCookies()) {

driver.manage().addCookie(c);
}

<Step3 : Actions with driver in continuation of Step2>

Thanks Google! for helping me to solve this.

Hope you got an idea about this, please share !

 

Thanks

To view or add a comment, sign in

More articles by SYAGINKUMAR AG

  • Scroll Page : in Selenium

    Hello All, While reading the title you will think that this is so simple ! Yah ! it's simple, if it is a normal…

Insights from the community

Others also viewed

Explore topics