切换框架的最佳做法是什么?

时间:2019-01-25 10:51:45

标签: java selenium google-chrome firefox webdriver

我在selenium webdriver中使用java,并且在被测试的应用程序中有很多框架。

这是我切换帧的代码:

ClientPg.waitLong(1);
ClientPg.getWindowHandle();
ClientPg.switchToDefaultContent();


public void getWindowHandle() {

    for (String winHandle : driver.getWindowHandles()) {
        driver.switchTo().window(winHandle);
    }

    driver.manage().window().maximize();
        reportLog("Switch to new window. Title : " + driver.getTitle());
    }

    public void switchToDefaultContent() {
        driver.switchTo().defaultContent();
    }
}

使用chrome时,其工作方式如下:

ClientPg.waitLong(1);
ClientPg.getWindowHandle();

但是在firefox中,我需要添加

:switchToDefaultContent();

1 个答案:

答案 0 :(得分:0)

您可以使用以下方式切换到效果良好的特定I框架。

要切换到垂直IFrame,请使用以下功能

public void switchframeByXpath(String xpath) throws Exception {

        try {
            System.out.println("switch to iframe");
            //wait for i frame element to load.
            WebDriver x = driver.switchTo().frame(driver.findElement(By.xpath(xpath)));
        } catch (Exception e) {
            throw new AssertionError("Can not Switch Iframe", e);
        }
    } 

要切换到主机,请使用以下功能

public void switchToMainFrame() {

        try {

            System.out.println("Before switching -- Switch to Main Frame");
            driver.switchTo().defaultContent();
            System.out.println("After switching -- Switch to Main Frame");
            Thread.sleep(1000);

        } catch (Exception e) {
            System.err.println("Can not Switch " + e.getMessage());
            throw new AssertionError("Switched to main Frame Error");
        }

    }