selenium-java,定位并操作frame和iframe内的元素

因为frame和iframe的原因,在frame里的元素不能直接定位需要切到相应的frame才可以对元素进行操作,下面是涉及的方法

webDriver.switchTo().defaultContent();//切回body
webDriver.switchTo().frame(int arg0);//切至本层第i个frame,arg0=i-1;
webDriver.switchTo().frame(String arg0);//切至本层id或name为arg0的frame
webDriver.switchTo().frame(WebElement arg0);//切至定位为arg0的frame
webDriver.switchTo().parentFrame();//返回父类frame

例子1,需要操作iframe里的input

<html>
<body>
<iframe id='iframe1' name='iframe1'>
<input id='1'></input>
</iframe>
</body>
</html>
webDriver.switchTo().frame(0);
//webDriver.switchTo().frame("iframe1");
webDriver.findElement(By.id("1")).sendKeys("1");

例子2,iframe内嵌iframe,操作iframe2里的input

iframe需要一个个切入,先切入iframe1才可以切入iframe2

<html>
<body>
<iframe id='iframe1' name='iframe1'>
<input id='1'></input>
<iframe id='iframe2' name='iframe2'>
<input id='2'></input>
</iframe>
</iframe>
</body>
</html>
webDriver.switchTo().frame(0);
//webDriver.switchTo().frame("iframe1");
webDriver.switchTo().frame(0);
//webDriver.switchTo().frame("iframe2");
webDriver.findElement(By.id("2")).sendKeys("2");
原文地址:https://www.cnblogs.com/yanzhe/p/7646347.html