selenium 常用的显式等待

来源:互联网 发布:惠普打印机安卓软件 编辑:程序博客网 时间:2024/06/06 03:07

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>() {@Overridepublic 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>() {@Overridepublic 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}



0 0
原创粉丝点击