Home > Software design >  if i create WebDriver obj in a loop how to manage or access each webDriver?
if i create WebDriver obj in a loop how to manage or access each webDriver?

Time:09-08

I have sample below,

for(i = 0; i < 5; i  )
{
    WebDriver driver = new ChromeDriver(options);
    i  ;
}

This code opens multiple browsers, My problem is i can't access each browser, For instance 5 browser has been opened, And I have to execute a js script in the 3rd browser, Is it possible or is there any ways to create instance with different name?

Thanks in advance

CodePudding user response:

Just capture each instantiation of WebDriver in an array (or List). Also you are incrementing i twice

WebDriver[] webDrivers = new WebDriver[5];
for(int i = 0; i < webDrivers.length ; i  )
{
    webDrivers[i] = new ChromeDriver(options);
}

WebDriver webDriver3 = webDrivers[2];

CodePudding user response:

You can put these objects in a List etc and after that to access them in that list, as following:

List<WebDriver> drivers = new ArrayList<>();
for(i = 0; i < 5; i  )
{
    WebDriver driver = new ChromeDriver(options);
    drivers.add(driver);
}

After that you can access the objects in this way:

drivers.get(0)

BTW, no need to increment the i index inside the loop

  • Related