How to switch between frames in Selenium WebDriver using Java

后端 未结 7 1800
轮回少年
轮回少年 2020-11-22 13:31

I am using java with WebDriver.I have to switch between two frames. I have recorded the test case in selenium IDE and in that I got the values as selectFrame relative=top se

7条回答
  •  执念已碎
    2020-11-22 14:02

    This code is in groovy, so most likely you will need to do some rework. The first param is a url, the second is a counter to limit the tries.

    public boolean selectWindow(window, maxTries) {
        def handles
        int tries = 0
        while (true) {
            try {
                handles = driver.getWindowHandles().toArray()
                for (int a = handles.size() - 1; a >= 0 ; a--) { // Backwards is faster with FF since it requires two windows
                    try {
                        Log.logger.info("Attempting to select window: " + window)
                        driver.switchTo().window(handles[a]);
                        if (driver.getCurrentUrl().equals(window))
                            return true;
                        else {
                            Thread.sleep(2000)
                            tries++
                        }
                        if (tries > maxTries) {
                            Log.logger.warn("Cannot select page")
                            return false
                        }
                    } catch (Exception ex) {
                        Thread.sleep(2000)
                        tries++
                    }
                }
            } catch (Exception ex2) {
                Thread.sleep(2000)
                tries++
            }
        }
        return false;
    }
    

提交回复
热议问题