Waits in Selenium


 
Explicit, implicit, and fluent waits are three types of waits that can be used in Selenium to synchronize the test script with the web page.

  1. Explicit wait: Explicit waits are used to wait for a certain condition to occur before performing the next action in the test script. This is achieved using the WebDriverWait class in Selenium. You can specify a maximum time to wait for the condition, and the script will keep checking for the condition until it is met or the timeout occurs. Some common expected conditions include the presence, visibility, and clickability of an element.

Here is an example of using explicit wait in Selenium:

WebDriverWait wait = new WebDriverWait(driver, 10); WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("example-id"))); element.click();

This code waits for up to 10 seconds for the element with ID "example-id" to be present on the page. Once the element is found, the script clicks on it.

  1. Implicit wait: Implicit waits are used to set a default timeout for all the elements in the test script. This means that if an element is not found immediately, Selenium will wait for the specified amount of time before throwing an exception. You can set an implicit wait using the WebDriver's manage() method.

Here is an example of using implicit wait in Selenium:

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); WebElement element = driver.findElement(By.id("example-id")); element.click();

This code sets a default implicit wait of 10 seconds. If the element with ID "example-id" is not found immediately, Selenium will wait for up to 10 seconds before throwing an exception.

  1. Fluent wait: Fluent waits are used to create a more customized wait condition. You can specify the polling interval, maximum wait time, and expected condition using the Wait interface. Fluent wait is useful when you need to wait for a dynamic condition that may change over time.

Here is an example of using fluent wait in Selenium:

Wait wait = new FluentWait(driver) .withTimeout(Duration.ofSeconds(10)) .pollingEvery(Duration.ofMillis(500)) .ignoring(NoSuchElementException.class); WebElement element = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(By.id("example-id")); } }); element.click();

This code creates a fluent wait that waits for up to 10 seconds, checks for the element every 500 milliseconds, and ignores the NoSuchElementException. Once the element is found, the script clicks on it.

No comments:

Post a Comment

Tips to improve Selenium Code

Intro to Selenium Selenium is an open-source testing framework used for automating web browsers. It allows testers to write scripts in vario...