selenium+Java处理iframe切换有3种方法:
1、如果iframe有id或name,则可根据iframe的id或name切换。
2、把iframe当作页面元素,通过元素定位表达式进行切换。
3、将iframe存储到list中,然后根据ifrane的索引定位 (适合页面有多个iframe,且前两种方法无法使用)。
如果页面有多层iframe嵌套,则需要一层一层往内切换,切出iframe则只需要一次操作。selenium+Java具体Java代码示例如下:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
public class Iframe {
public static void main(String[] args) {
// 启动浏览器,访问目标网页,窗口最大化
System.setProperty("webdriver.chrome.driver", "webdrivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.team.cn");
driver.manage().window().maximize();
// 切换到iframe中,针对多层嵌套的iframe,需要一层一层往里切换,切出去只需一次
// 方法:1:根据iframe的id或name切换
driver.switchTo().frame("needit");
driver.switchTo().frame("ueditor_0");
// 切出iframe
driver.switchTo().defaultContent();
// 方法2:把iframe当作页面元素进行切换
WebElement iframe1 = driver.findElement(By.cssSelector("iframe.needit"));
driver.switchTo().frame(iframe1);
WebElement iframe2 = driver.findElement(By.cssSelector("iframe[frameborder='0']"));
driver.switchTo().frame(iframe2);
// 切出iframe
driver.switchTo().defaultContent();
// 方法3:将iframe存储到list中,然后根据ifrane的索引定位
List<WebElement> iframeElements = driver.findElements(By.tagName("iframe"));
System.out.println("iframe List的长度是:"+iframeElements.size());
driver.switchTo().frame(0);
driver.switchTo().frame(1);
// 切出iframe
driver.switchTo().defaultContent();
// 关闭浏览器
driver.quit();
}
}