如何使用Selenium对子iFrame执行操作?

时间:2013-01-21 07:03:12

标签: java iframe selenium selenium-webdriver

我们如何在iFrame中的iFrame上执行操作?

HTML:

<div id="div1">
 <iframe id="iframe1">
   <div id="div2">
     <iframe id="iframe2">
     </iframe>
   </div>
   <div id="div3">
     <iframe id="iframe3">
     </iframe>
   </div>
 </iframe>
</div>

我需要对iframe2和iframe3执行操作。尝试使用以下代码:

1. driver.switchTo().frame("iframe1.0.iframe2");
2. WebElement firstFrame = driver.findElement(By.id("iframe1"));
   driver.switchTo().frame(firstFrame);
   WebElement secondFrame = driver.findElement(By.id("iframe2"));
   driver.switchTo().frame(secondFrame);

但无法解决问题。

请建议是否采用其他方法。

2 个答案:

答案 0 :(得分:0)

试试这个

//switch the control to first frame
WebElement firstFrame = driver.findElement(By.id("iframe1"));
driver.switchTo().frame(firstFrame);

//switch the control to second frame
WebElement secondFrame = driver.findElement(By.id("iframe2"));
driver.switchTo().frame(secondFrame);

//Switch back the control to first frame before switch it to frame3
driver.switchTo().frame(firstFrame);

WebElement thirdFrame = driver.findElement(By.id("iframe3"));
driver.switchTo().frame(thirdFrame);

答案 1 :(得分:0)

试试这个代码段。

 //Switch To parent frame "iframe1"
 WebElement parentFrame = driver.findElement(By.id("iframe1"));
 driver.switchTo.frame(parentFrame );

 //Switch To first child frame "iframe2"
 WebElement firstChildFrame = driver.findElement(By.id("iframe2"));
 driver.switchTo.frame(firstChildFrame ); 

 //Do some actions on iframe2
 //Switch To Top (or) Parent frame by using
 driver.switchTo().defaultContent();

 //Switch To parent frame "iframe1"
 WebElement parentFrame = driver.findElement(By.id("iframe1"));
 driver.switchTo.frame(parentFrame );

 //Switch To second child frame "iframe3"
 WebElement secondChildFrame = driver.findElement(By.id("iframe3"));
 driver.switchTo.frame(secondChildFrame); 

有关选择框架的更多详细信息,请使用此http://darrellgrainger.blogspot.ca/2012/04/frames-and-webdriver.html