1.实例的html源码
<html>
<head>
<title>你喜欢的水果</title>
</head>
<body>
<p>请选择你爱吃的水果</p><br>
<select name='fruit'>
<option id='peach' value ='taozi'>桃子</option>
<option id='watermelon' value='xigua'>西瓜</option></select>
<br>
<input type='checkbox'>是否喜欢吃水果?</input><br><br>
<input type="text" id ="text" value="今年夏天西瓜相当甜!">文本框</input>
</body>
</html>
2.java实例代码
//声明一个webdriverWait对象,设定触发条件的最长等待时间为10秒
WebDriverWait wait = new WebDriverWait(driver, 10);
//调用ExpectedConditions的titleContains方法判断页面Title属性是否包含“水果”两字
wait.until(ExpectedConditions.titleContains("水果"));
System.out.println("网页标题出现了水果的关键字");
//获得页面下拉列表中的桃子选项对象
WebElement select = driver.findElement(By.xpath("//option[@id='peach']"));
//调用ExpectedConditions的elementToBeSelected方法,判断桃子是否处于选定状态
wait.until(ExpectedConditions.elementToBeSelected(select));
System.out.println("下拉列表的选项桃子目前处于选中状态");
/*调用expectContains的elementtobeclickable方法判断页面的复选框是否可见,并且可以被单击*/
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@type='checkbox']")));
System.out.println("页面复选框处于显示可被单击的状态");
//调用ExpectedContditions的presenceOfElementLocated的方法判断标签p是否在页面中
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//p")));
System.out.println("页面的P标签元素已显示");
WebElement p = driver.findElement(By.xpath("//p"));
wait.until(ExpectedConditions.textToBePresentInElement(p, "爱吃的水果"));
3.自定义显式等待
try {
//显式等待判断是否可以从页面获取输入文字的输入框对象,乳沟可以获取,则执行后续逻辑测试
WebElement textIputBox = (new WebDriverWait(driver, 10)).until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver d){
return d.findElement(By.xpath("//*[@type='text']"));
}
});
//断言获取页面输入框中是否包含“今年的西瓜想当甜!”这几个关键字
Assert.assertEquals("今年夏天西瓜相当甜!", textIputBox.getAttribute("value"));
//判断页面的P标签中是否包含爱吃两个字,若包含则执行后续的测试逻辑
Boolean containTextFlag =(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver d){
return d.findElement(By.xpath("//p")).getText().contains("爱吃");
}
});
Assert.assertTrue(containTextFlag);
//显式等待判断页面的文本输入框是否可见,若可见则执行后续测试逻辑
Boolean inputBoxVisibleFlag = (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(By.xpath("//*[@type='text']")).isDisplayed();
}
});
Assert.assertTrue(inputBoxVisibleFlag);
} catch (NoSuchElementException e) {
Assert.fail("页面上的输入框元素未被找到!");
e.printStackTrace();
// TODO: handle exception
}