页面html代码如下:
<!doctype html>
<html lang="en">
<head>
<title>frameset page title</title>
</head>
<frameset cols = "25%,50%,25%">
<frame id="leftframe" src ="frame_left.html"/>
<frame id="middleframe" src ="frame_middle.html"/>
<frame id="rightframe" src ="frame_right.html"/>
</frameset>
<body>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<title>left frame</title>
</head>
<body>
<p>this is left frame text</p>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<title>middle frame title</title>
</head>
<body>
<p> this is middle frame text</p>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<title>right frame title</title>
</head>
<body>
<p> this is right frame text</p>
</body>
</html>
页面效果如下
@Ignore
public void testHandleFrame(){
driver.get("E:\\Java\\selenium_data\\html\\frameset_demo.html");
driver.switchTo().frame("leftframe");
WebElement leftFrameText = driver.findElement(By.xpath("//p"));
Assert.assertEquals("this is left frame text", leftFrameText.getText());
//如果不调用defaultContent()方法,frame无法切换到其他frame中
driver.switchTo().defaultContent();
//frame(int index)方法调用切换frame
driver.switchTo().frame(1);
System.out.println(driver.findElement(By.xpath("//p")).getText());
}
@Test
public void testHandleFrameByPageSource(){
driver.get("E:\\Java\\selenium_data\\html\\frameset_demo.html");
List<WebElement> frames = driver.findElements(By.tagName("frame"));
for(WebElement frame:frames){
driver.switchTo().frame(frame);
if(driver.getPageSource().contains("middle frame")){
Assert.assertEquals("this is middle frame text", driver.findElement(By.xpath("//p")));
}else{
driver.switchTo().defaultContent();
}
}
driver.switchTo().defaultContent();
}