WebDriverWait,配合該類的until()和until_not()方法,就可以根據判斷條件而進行靈活地等待了。app
程序每隔xx秒看一眼,若是條件成立了,則執行下一步,不然繼續等待,直到超過設置的最長時間,而後拋出TimeoutException。ide
//頁面元素是否在頁面上可用和可被點擊 ExpectedConditions.elementToBeClickable(By locator); //頁面元素是否處於被選中狀態 ExpectedConditions.elementToBeSelected(By locator); //頁面元素在頁面是否存在 ExpectedConditions.presenceOfElementLocated(By locator); //是否包含特定的文本 ExpectedConditions.textToBePresentInElement(locator, text) //頁面元素值 ExpectedConditions.textToBePresentInElementValue(locator, text); //標題 ExpectedConditions.titleContains(title);
public static void sendKeysByXPath(WebDriver driver, String path, String key) { WebDriverWait wait = new WebDriverWait(driver, 10); // 最多等10秒 WebElement element = wait.until(new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver d) { return d.findElement(By.xpath(path)); } }); highLightElement(driver,element); element.clear(); element.sendKeys(key); }
FluentWait:能夠動態設置巡檢時間spa
//FluentWait Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(60, TimeUnit.SECONDS) .pollingEvery(2, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class); WebElement ele1 = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(By.id("xxxxxxx")); } });
設置超時時間,等待頁面加載,若是在規定時間加載完成就執行下一步;code
弊端:須要等整個頁面加載完成,才能執行下一步對象
週期:對driver整個週期都適用,執行一次便可blog
pageLoadTimeout.頁面加載超時時間ci
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Thread.sleep(2000);