selenium 常用的显式等待

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
		}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值