一、iframe 内联框架
1.自己写个网页,仅供理解iframe演示使用,如下
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>iframeA</title> <style type="text/css"> div { border:2px solid red; width: 800px; height: 350px; } #iframe_a { border:2px solid red; width: 500px; height: 300px; } </style> </head> <body> <div> <br>iframeA: <input id='input_a' type='text'> <iframe id='iframe_a' name='iframe_a_name' class='iframe_cls' src="./iframeB.html"></iframe> <br> </div><br> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>iframeB</title> <style type="text/css"> div { width: 400px; height: 200px; } #iframe_b { width: 300px; height: 100px; } </style> </head> <body> <div> <br> iframeB: <input id='input_b' type='text'> <iframe id='iframe_b' name='iframe_b_name' src="./iframeC.html"></iframe> </div> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>iframeC</title> </head> <body> <div> <br>iframeC: <input id='input_c' type='text'> </div> </body> </html>
展示如下:
2.依次写入iframeA输入框,iframeB输入框,iframeC输入框代码实现
driver.navigate().to("file:///D:/xxx/test_html/iframeA.html"); driver.findElement(By.id("input_a")).sendKeys("iframe_A"); //切换iframe;将驱动对象的作用域切换至b页面 driver.switchTo().frame("iframe_a");//传入iframe_id进行切换 driver.findElement(By.id("input_b")).sendKeys("iframe_B"); WebElement element = driver.findElement(By.id("iframe_b")); //切换iframe driver.switchTo().frame(element);//传入iframe元素进行切换 driver.findElement(By.id("input_c")).sendKeys("iframe_C");
注意:iframe只能是按照顺序层级切换,不能从iframe_A直接切换至iframe_C
3.当你写入iframe_C的时候,返回iframe_B修改写入文本值,再返回iframe_A修改输入的文本值,代码实现;
//切换父节点:parentiframe driver.switchTo().parentFrame(); driver.findElement(By.id("input_b")).clear(); driver.findElement(By.id("input_b")).sendKeys("C返回父节点B,修改iframe_B"); driver.switchTo().parentFrame(); driver.findElement(By.id("input_a")).clear(); driver.findElement(By.id("input_a")).sendKeys("B返回父节点A,修改iframe_A");
4.直接返回切换到顶级的父节点iframe例如:C输入后,直接切换到A文本框输入:
/** WebDriver org.openqa.selenium.WebDriver.TargetLocator.defaultContent() Selects either the first frame on the page, or the main document when a page contains iframes. Returns:This driver focused on the top window/first frame. **/ driver.switchTo().defaultContent();
//直接返回切换到顶级的父节点iframe例如:C输入后,直接切换到A文本框输入: driver.switchTo().defaultContent(); driver.findElement(By.id("input_a")).clear(); driver.findElement(By.id("input_a")).sendKeys("C直接切顶级A,再次修改iframe_A");
5.学习后总结,不足之处后续补充修正!