selenium 多表单切换处理(iframe/frame)

在web应用中,前台网页的设计一般会用到iframe/frame表单嵌套页面的应用。简单的就是一个页面签嵌套多个HEML/JSP文件。selenium webdriver  只能在同一页面识别定位元素,可以狭隘的理解成只能识别当前所在位置的页面上的元素。对于不同的iframe/frame表单中的元素是无法直接定位的。需要结合switchTo().frame()方法切换到指定的frame/iframe中。switchTo().frame()默认的是取表单的ID和name属性。如果没有id和name ,可通过Xpath路径定位。

对表单操作完成之后可以通过driver.switchTo().defaultContent();跳出表单。

以下是练习窗口切换的指定表单的HTML代码。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>窗口切换</title>
</head>
<frameset rows="15%,*,15%" ,border="0" scrolling="no"
    noresize="noresize">
    <frame src="https://www.baidu.com/" name="top" noresize="noresize" />
    <frame src="http://www.sina.com.cn/" name="body" />
    <frame src="https://www.taobao.com/" name="bottom" />
</frameset>
</frameset>
</html>
    public static void main(String[] args) {

        System.setProperty("webdriver.firefox.bin", "D:\Mozilla Firefox\firefox.exe");

        WebDriver driver = new FirefoxDriver();
        File file = new File("C:\Users\Administrator\Desktop\NewFile.html");
        driver.get(file.getAbsolutePath());
        driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
        // 设置页面加载时间为5秒
        driver.switchTo().frame("top");
        // 表单切换到最顶层的frame中。
        driver.findElement(By.id("kw")).sendKeys("selenium学习");
        // 在百度输入框中输入selenium学习
        driver.switchTo().defaultContent();
        // 返回到上一级表达
        driver.switchTo().frame("body");
        // 切换到中间表单,name="body"
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        driver.findElement(By.linkText("房产")).click();
        driver.switchTo().defaultContent();
        // 每次进入一个表单。操作元素之后 ,尽量跳回上一层或者最外层再进入其它表达操作元素。
        driver.close();
        driver.quit();

    }
原文地址:https://www.cnblogs.com/linxinmeng/p/6938615.html