Explicit Waits: 显式等待, 在规定时间内等待元素出现,元素出现则返回元素,如果规定时间内没有返回,则跑出异常。
WebDriver driver = new FirefoxDriver(); driver.get("http://somedomain/url_that_delays_loading"); WebElement myDynamicElement = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));
This waits up to 10 seconds before throwing a TimeoutException or if it finds the element will return it in 0 - 10 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return value for the ExpectedCondition function type is a Boolean value of true, or a non-null object.
Expected Conditions
There are some common conditions that are frequently encountered when automating web browsers. Listed below are a few examples for the usage of such conditions.
- Element is Clickable - it is Displayed and Enabled.
WebDriverWait wait = new WebDriverWait(driver, 10); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
- presenceOfElementLocated(一个只要一个符合条件的元素加载出来就通过)
new WebDriverWait(driver, 15).until(ExpectedConditions.presenceOfElementLocated(By.id("someid")));
- textToBePresentInElementLocated
new WebDriverWait(driver,15).until(ExpectedConditions.textToBePresentInElementLocated(By.id("someid"), CVGUI.loginLnkLabel));
- visibilityOfElementLocated
new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOfElementLocated(By.id(“someid”)));
Imlicitly Wait:隐式等待
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("http://somedomain/url_that_delays_loading"); WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
Thread.sleep(): 线程休眠