显示等待可以在执行下一次操作时,自定义等待条件
显示的等待只需要执行在需要同步的地方而不影响脚本的其他地方
Selenium WebDriver提供了WebDriverWait和ExpectedCondition类来执行显示等待
ExpectedCondition类提供了一系列预定义好的条件来等待。下面是一些常用的条件
预定义条件 | 方法名 |
元素可见可点击 | elementToBeClickable(By locator) |
元素可被选中 | elementToBeSelected(WebElement element) |
存在一个元素 | presenceOfElementLocated(By locator) |
元素中出现指定的文本 | textToBePresentInElement(By locator) |
元素的值 | textToBePresentInElementValue(By locator, String text) |
标题 |
titleContains(String title) |
WebDriverWait每500毫秒调用一次ExpectedCondition直到得到正确的返回值。这样的好处是随时控制所需呀等待的地方,更加精确的控制等待条件
public void testWithImplicitWait(){
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://map.baidu.com"); WebElement curCity = driver.findElement(By.id("curCity"));
curCity.click(); //设置等待时间10秒
WebDriverWait wait = new WebDriverWait(driver,10);
//等待直到符合元素文本内容出现
wait.until(ExpectedConditions.textToBePresentInElement(By.id("selCityHotCityId"), "全国")); driver.quit();
}
示例代码