【selenium】 隐式等待与显示等待

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/galen2016/article/details/84347750

简介:总结selenium的隐式等待与显式等待

隐式等待

设置一个默认的操作等待时间,即每个操作的最大延时不超过该时间

  • 常用的隐式等待
//页面加载超时时间
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
//元素定位超时时间
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//异步脚本超时时间
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);

显式等待

  • 显式等待就是在设置的时间之内,要等到满足某个元素的某个条件,该条件满足后就往下执行代码,如果超出设置的时间还没满足条件,那么就抛出Exception。
  • 显式等待使用ExpectedConditions类中的方法, 可以设置显试等待的条件
  • ExpectedConditions方法
方法 描述
elementToBeClickable(By locator) 页面元素是否在页面上可用和可被单击
elementToBeSelected(WebElement element) 页面元素处于被选中状态
presenceOfElementLocated(By locator) 页面元素在页面中存在
textToBePresentInElement(By locator) 在页面元素中是否包含特定的文本
textToBePresentInElementValue(By locator, java.lang.String text) 页面元素值
titleContains(java.lang.String title) 标题 (title)
  • 使用实例
	/**
	 * 判断元素是否存在
	 * @param driver
	 * @param ele 等待的元素
	 * @return boolean 是否存在
	 */
	public static boolean isElementExsit(WebElement ele,WebDriver driver) {
        boolean flag ;
        try {  
        	WebDriverWait wait = new WebDriverWait(driver,20);
			WebElement element = wait.until(ExpectedConditions.visibilityOf(ele));
			flag = element.isDisplayed();
        } catch (Exception e) {  
        	flag = false;
            System.out.println("Element:" + ele.toString()  
                    + " is not exsit!");  
        }  
        return flag;  
    } 
	
	/**
	 * 通过元素的Xpath,等待元素的出现,返回此元素
	 * @param driver
	 * @return 返回等待的元素
	 */
	public static WebElement waitByXpath(String xpath,WebDriver driver){
		WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
		//presenceOfElementLocated:显示等待,页面元素在页面中存在,不用等页面全部加载完
		WebElement targetElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
		return targetElement;
	}

猜你喜欢

转载自blog.csdn.net/galen2016/article/details/84347750