How to move selenium webdriver to another tab of the browser and click on button within iframeAsk Question

问题:

I am trying to automate 1 scenario where if I click on button on webpage it opens another tab in the browser. I am trying to move my webdriver to another tab but with no success. And also I want to click on the button which is within iframe. HEre is my code:

ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
        driver.switchTo().window(tabs2.get(2));
        driver.switchTo().frame(0);
        click(buttonwithiniframe);

Any help is really appreciated!

回答1:


Try to wait for a new window before switching to it. Moreover, selecting a window by index is not reliable.

This example switches to a newly opened window and set the context on the first frame:

import org.openqa.selenium.support.ui.WebDriverWait;


WebDriverWait wait = new WebDriverWait(driver, 20);

// get the main window handle
String mainHandle = driver.getWindowHandle();

// wait for a new window and switch to it
driver.switchTo().window(wait.until((WebDriver drv)->{
    for (String handle : drv.getWindowHandles()){
        if (!handle.equals(mainHandle))
            return handle;
    }
    return null;
}));

// set the context on the first frame
driver.switchTo().frame(0);

And to wait for a new window without lambda expression:

// wait for a new window and switch to it
driver.switchTo().window(wait.until(new ExpectedCondition<String>() {
    @Override
    public String apply(WebDriver drv) {
        for (String handle : drv.getWindowHandles()){
            if (!handle.equals(mainHandle))
                return handle;
        }
        return null;
    }
}));
标签: selenium iframe browser
© 2014 TuiCode, Inc.