采用下面的例子来编写用例
frame switch frame
代码:
package com.test.frame;import org.openqa.selenium.By;import org.openqa.selenium.JavascriptExecutor;import org.openqa.selenium.NoSuchElementException;import org.openqa.selenium.WebDriver;import org.openqa.selenium.firefox.FirefoxDriver;import org.openqa.selenium.support.ui.ExpectedConditions;public class frameSwitch { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("file:///D:/10-selenium/workspace/SeleniumTest/src/com/test/frame/frame.html"); driver.manage().window().maximize(); // 利用id来切换 waitTime(2000); driver.switchTo().frame("if"); waitTime(2000); if (driver.findElement(By.xpath("//*[@id='kw']")).isDisplayed()) { driver.findElement(By.xpath("//*[@id='kw']")).sendKeys("switch successfully"); // 切换到父frame driver.switchTo().parentFrame(); try { driver.findElement(By.xpath("//*[@id='kw']")); } catch (NoSuchElementException e) { String js = "alert(\"switch to parent\")"; ((JavascriptExecutor) driver).executeScript(js); waitTime(3000); driver.switchTo().alert().dismiss(); } } // 利用name来切换 waitTime(2000); driver.switchTo().frame("nf"); waitTime(2000); if (driver.findElement(By.xpath("//*[@id='kw']")).isDisplayed()) { driver.findElement(By.xpath("//*[@id='kw']")).sendKeys("switch successfully"); driver.switchTo().parentFrame(); try { driver.findElement(By.xpath("//*[@id='kw']")); } catch (NoSuchElementException e) { String js = "alert(\"switch to parent\")"; ((JavascriptExecutor) driver).executeScript(js); waitTime(3000); driver.switchTo().alert().dismiss(); } } // 利用定位元素来切换-xpath waitTime(2000); driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@id='if']"))); waitTime(2000); if (driver.findElement(By.xpath("//*[@id='kw']")).isDisplayed()) { driver.findElement(By.xpath("//*[@id='kw']")).sendKeys("switch successfully"); driver.switchTo().parentFrame(); try { driver.findElement(By.xpath("//*[@id='kw']")); } catch (NoSuchElementException e) { String js = "alert(\"switch to parent\")"; ((JavascriptExecutor) driver).executeScript(js); waitTime(3000); driver.switchTo().alert().dismiss(); } } // 利用定位元素来切换-css waitTime(2000); driver.switchTo().frame(driver.findElement(By.cssSelector("#if"))); waitTime(2000); if (driver.findElement(By.xpath("//*[@id='kw']")).isDisplayed()) { driver.findElement(By.xpath("//*[@id='kw']")).sendKeys("switch successfully"); driver.switchTo().parentFrame(); try { driver.findElement(By.xpath("//*[@id='kw']")); } catch (NoSuchElementException e) { String js = "alert(\"switch to parent\")"; ((JavascriptExecutor) driver).executeScript(js); waitTime(3000); driver.switchTo().alert().dismiss(); driver.quit(); } } } static public void waitTime(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}