简体   繁体   中英

How to switch tab using for loop in Selenium Webdriver

I struggle with the problem of not being able to switch between tabs using the loop in Selenium WebDriver. I can do this at once, but I need to use the code repeatedly, in a loop.

Here comes the error:

"Exception in thread" main "org.openqa.selenium.NoSuchWindowException: Unable to locate window"

My code can find all the elements, open a link in a new tab, close it. However, it can not perform this operation again with the next element.

Here is my code( I'm using Firefox):

List<WebElement> allElements = driver.findElements(By.className("_4zhc5"));
    int s = allElements.size();
    
    System.out.println("total users to check: " + allElements.size());
    for (int i = 0; i < s; i++) {
        
        
        
        allElements = driver.findElements(By.className("_4zhc5"));
        String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
        allElements.get(i).sendKeys(selectLinkOpeninNewTab);
        
    
        for (String winHandle : driver.getWindowHandles()) {
            driver.switchTo().window(winHandle);
            Thread.sleep(3000);
             
        }

         
        
         driver.close();
         Thread.sleep(2000);

    }

I also created a prototype page using jsfiddle . The error appears on the second attempt to execute the code. Just the script does not click on another element called "lovely"

You need to switch back to the original window where the links are.

  1. Click on one if the links
  2. Switch to that tab
  3. Close tab
  4. Switch back to default window where you are getting the links

Easiest way is to store the "original" window and switch back to that one all the time. winHandleBefore = driver.getWindowHandle();

when closing the tab

driver.close(); 

driver.switchTo().window(winHandleBefore)

/*the second "for loop" will not help you so u should use another logic with another condition it will switch using while loop and hasNext method try it: */

List allElements = driver.findElements(By.className("_4zhc5"));

int s = allElements.size();
System.out.println("total users to check: " + allElements.size());
for (int i = 0; i < s; i++) {
    allElements = driver.findElements(By.className("_4zhc5"));
    String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
    allElements.get(i).sendKeys(selectLinkOpeninNewTab);
    Set<String>windowat=driver.getWindowHandles();
    Iterator<String>itro=windowat.iterator();
    while(itro.hasNext()) {
        String currntpage=itro.next();
        driver.switchTo().window(currntpage);
        String thetitle=driver.getTitle();
        System.out.println(thetitle); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM