您的位置:首页 > 其它

Selenium学习9--显示等待,判断页面元素是否存在

2016-09-15 16:58 573 查看
html代码如下:

<html lang="en">
<head>
<title>your favorite fruits</title>
</head>
<body>
<p>select ur perfer fruit</p>
<br>
<select name='fruit'>
<option id='peach' value='taozi'>peach</option>
<option id='watermelon' value='xigua'>watermelon</option>
</select>
<br>
<input type='checkbox'>Do you like fruits?</input>
<br><br>
<input type=text" id="text" value="Watermelons are so sweet this year!">This is Input box</input>
</body>
</html>


@Test
public void testExplicitWait(){
driver.get("E:\\Java\\selenium_data\\html\\obviouswait.html");
//声明一个WebDriverWait对象,设定复发条件的最长时间待定10s
WebDriverWait wait = new WebDriverWait(driver,10);
//调用ExpectedConditions的titleContains方法判断页面title属性是否包含"fruits"字段
wait.until(ExpectedConditions.titleContains("fruits"));

WebElement select = driver.findElement(By.xpath("//option[@id='peach']"));
//elementToBeSelected(Element element)判断"peach"是否被选中
wait.until(ExpectedConditions.elementToBeSelected(select));

//elementToBeClickable(String )判断复选框对象是否可以被点击
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//p")));

//presenceOfElementLocated 判断元素是否存在
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//x")));

//textToBePresentInElement判断字样是否在元素中显示
WebElement p = driver.findElement(By.xpath("//p"));
wait.until(ExpectedConditions.textToBePresentInElement(p, "select ur perfer fruit"));
}


自定义显示等待

@Test
public void testCustomExplicitWait(){
driver.get("E:\\Java\\selenium_data\\html\\obviouswait.html");
try{
//显示等待判断是否可以从页面获取文字输入框对象, 如果可以获取, 则执行后续测试逻辑
WebElement textInputBox = (new WebDriverWait(driver,10).until(new ExpectedCondition<WebElement>() {

@Override
public WebElement apply(WebDriver driver) {
return driver.findElement(By.xpath("//*[@type='text']"));
}
}));
Assert.assertEquals("Watermelons are so sweet this year!", textInputBox.getAttribute("value"));

Boolean containTextFlag = (new WebDriverWait(driver,10).until(new ExpectedCondition<Boolean>() {

@Override
public Boolean apply(WebDriver driver) {
return driver.findElement(By.xpath("//p")).getText().equals("perfer fruit");
}
}));
Assert.assertTrue(containTextFlag);

}catch(Exception e){
e.printStackTrace();
}
}


判断页面元素是否存在

private boolean isElementPresent(By by){
try{
driver.findElement(by);
return true;
}catch(Exception e){
return false;
}

}

@Test
public void testIsElementPresent(){
driver.get("http://www.sogou.com");
if(isElementPresent(By.id("query"))){
WebElement searchInputBox = driver.findElement(By.id("query"));
if(searchInputBox.isEnabled()){
searchInputBox.sendKeys("元始金章");
}
}else{
Assert.fail("元素没有找到,zz");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  selenium