判断页面元素是否存在
测试网址
http://www.baidu.com
Java语言版本API实例
@Test
public void testIsElementPresent(){
driver.manage().window().maximize();
driver.get(url);
if(IsElementPresent(By.id("kw"))){
WebElement searchInputBox = driver.findElement(By.id("kw"));
if(searchInputBox.isEnabled() == true){
searchInputBox.sendKeys("百度首页搜索框成功找到");
}
}
else{
Assert.fail("未找到页面元素");
}
}
private boolean IsElementPresent(By by) {
try {
//判断传入的参数是否找到页面元素,找到则返回true
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
使用title属性识别和操作弹出的浏览器窗口
测试页面代码
<html>
<head>
<title>你喜欢的水果</title>
</head>
<body>
<p id='p1'>你爱吃的水果么?</P>
<br><br>
<a href="http://www.baidu.com" target="_blank">百度搜索</a>
</body>
</html>
http://www.baidu.com
Java语言版本API实例
@Test
public void identifyPopUpWindowByTitle() {
driver.manage().window().maximize();
driver.get(url);
//获取当前窗口句柄
String parentWindowHandle = driver.getWindowHandle();
WebElement baiduLink = driver.findElement(By.xpath("//a"));
baiduLink.click();
//定义一个set容器存储所有的窗口句柄
Set<String> allWindowsHandles = driver.getWindowHandles();
//如果存储容器对象不为空则进行遍历
if(!allWindowsHandles.isEmpty()){
for(String windowHandle:allWindowsHandles){
try {
//通过窗口的浏览器名称判断是否为百度
if(driver.switchTo().window(windowHandle).getTitle().equals("百度一下,你就知道"))
driver.findElement(By.id("kw")).sendKeys("百度的浏览器窗口被找到");
} catch (NoSuchWindowException e) {
e.printStackTrace();
}
}
}
//返回最早打开的窗口
driver.switchTo().window(parentWindowHandle);
//通过标题断言判断是否为之前窗口
Assert.assertEquals(driver.getTitle(), "你喜欢的水果");
}
使用页面的文字内容识别和处理新弹出的浏览器窗口
测试页面代码
<html>
<head>
<title>你喜欢的水果</title>
</head>
<body>
<p id='p1'>你爱吃的水果么?</P>
<br><br>
<a href="http://www.baidu.com" target="_blank">百度搜索</a>
</body>
</html>
Java语言版本API实例
@Test
public void identifyPopUpWindowByPageSource() {
String parentWindowHandle = driver.getWindowHandle();
driver.get(url);
WebElement baiduLink = driver.findElement(By.xpath("//a"));
baiduLink.click();
Set<String> allWindowHandles = driver.getWindowHandles();
if(!allWindowHandles.isEmpty()){
for(String windowHandle:allWindowHandles){
try {
//判断页面源码中是否包含百度一下4字
if(driver.switchTo().window(windowHandle).getPageSource().contains("百度一下"))
driver.findElement(By.id("kw")).sendKeys("找到百度浏览器窗口");
} catch (NoSuchWindowException e) {
e.printStackTrace();
}
}
}
//返回之前的浏览器窗口
driver.switchTo().window(parentWindowHandle);
Assert.assertEquals(driver.getTitle(), "你喜欢的水果");
}