Using Implicit Wait
Implicit wait is a technique used to tell Selenium to wait for a certain amount of time before throwing an exception. This wait is applied globally, which means it will be used throughout the entire lifecycle of the WebDriver instance. To use an implicit wait, you just need to call the method setImplicitWait() and specify the amount of time you want Selenium to wait before timing out.The following code demonstrates how to use implicit wait:
```WebDriver driver = new ChromeDriver();driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);driver.get(\"https://www.example.com\");```In the code above, we are initializing the WebDriver, setting the implicit wait to 10 seconds, and opening the website in the browser. If the website takes longer than 10 seconds to load, Selenium will throw a TimeOutException.
Using Explicit Wait
Explicit wait is another technique used to wait for a particular web element to appear on a page. With explicit wait, you can define a condition that must be met before the WebDriver moves to the next step. To use explicit wait, you need to create an instance of WebDriverWait and pass it to the ExpectedConditions class.The following code demonstrates how to use explicit wait:
```WebDriver driver = new ChromeDriver();driver.get(\"https://www.example.com\");WebDriverWait wait = new WebDriverWait(driver, 10);WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(\"example-username\")));```In the code above, we are initializing the WebDriver, opening the website, creating an instance of WebDriverWait with a timeout of 10 seconds, and waiting for the element with the ID \"example-username\" to become visible. If the element is not visible within 10 seconds, Selenium will throw a TimeOutException.
Using Fluent Wait
Fluent wait is a more advanced technique used to wait for a web element with a specific condition before moving to the next step. With fluent wait, you can define the frequency at which you want Selenium to check for the element and how long you want it to wait before timing out.The following code demonstrates how to use fluent wait:
```WebDriver driver = new ChromeDriver();driver.get(\"https://www.example.com\");WaitIn the code above, we are initializing the WebDriver, opening the website, creating an instance of FluentWait with a timeout of 30 seconds, polling every 2 seconds, ignoring NoSuchElementException, and waiting for the element with the ID \"example-username\" to be present. If the element is not present within 30 seconds, Selenium will throw a TimeOutException.