selenium嵌套定位
嵌套定位在日常测试当中也是比较常见的定位方式,但是一般任何的测试人员都不希望有这东西,因为这种嵌套定位比较麻烦,也比较难以发现。当你试过多种方式都定位不到该对象的时候不妨看看你所要定位的对象是否是内嵌网页的对象(frame)。在前端开发的过程中有很多网页并不是一个人开发的,有的是分工的。所以有一些网页是组合起来的,所以需要(driver.switchTo().frame(“frame1”);)函数切入进去再定位。但是切入进去之后记得切出来(driver.switchTo().defaultContent();),不然会你的操作会停留在内嵌页面中。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class frameLocation {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
String chromePath=System.getProperty("user.dir")
+"\\driver\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", chromePath);
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.hao123.com");
driver.findElement(By.cssSelector("#login > div > a > span")).click();
Thread.sleep(2000);
/*
* 定位frame后切入frame
*/
WebElement e=driver.findElement(By.cssSelector("#TANGRAM__PSP_5__ > iframe"));
driver.switchTo().frame(e);
driver.switchTo().defaultContent();//切出frame
}
}
注意:switchTo().frame();有三种用法;
1、传frame的id;
2、传frame的name;
3、传一个frame定位好的对象。