OfferTransform Your Career with Expert-Led IT Training. Flat discounts active!Explore Now
OnlineITGuru Logo
AI & Machine Learning

Selenium wait statements

Last updated on Jun 15, 2020

Copy Link:
Selenium wait statements

The last topic in the Selenium Tutorial is wait functions. While executing the test cases, this selenium wait statements plays a major role. And we people were familiar with wait() in programming languages like JAVA. But have you ever think of

Why do people use Wait () Selenium?

Today most of the web application uses Ajax and JAVA Script. And if the browser loads, it takes different times to load the elements. The reasons for taking the variable timings to load these elements depends on the variable factors.  Moreover, there are some cases where the element is not located at the location given in the code. At this time, this throws an ElementNotVisible Exception. So to avoid this problem, we use Wait().

What Wait() does?

It usually waits for a certain period of time for the element to load in the application. And it closes the application if the elements cannot be loaded in the given amount of time. The waits are usually classified into two types like

  1. Explicit Waits
  2. Implicit Waits

Implicit Waits ():

This wait tells the web driver to wait for a certain amount of time before it throws an exception. Once we set the time, the driver will wait for the time we have set, before it throws an exception. And one thing you should remember that the default is set to zero. And we need to mention some time to make web driver wait for the specified amount of time. The syntax for the implicit waits is shown below:

syntax:

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

This implicit wait accepts two parameters. The first parameter accepts time as an integer value and the second parameter accepts time measurement in terms of Days, hours, Minutes, Seconds, Milliseconds, Microseconds, Nano Seconds etc.

Execute the following  Online education code  in your IDE to perform the implicit Wait()

package SoftwareTesting; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; // import Web driver import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; // import Test import org.testng.annotations.Test; public class AppTest {

protected WebDriver driver; @Test public void seleniumtutorials() throws InterruptedException { System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" ); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ; String eTitle = "Selenium Tutorial | OnlineITGuru"; String aTitle = "" ; // launch Chrome and redirect it to the Base URL driver.get("https://onlineitguru.com/onlinetutorials/selenium" ); //Maximizes the browser window driver.manage().window().maximize() ; //get the actual value of the title aTitle = driver.getTitle(); //compare the actual title with the expected title if (aTitle.equals(eTitle)) { System.out.println( "Test Passed") ; } else { System.out.println( "Test Failed" ); } //close browser driver.close(); } }

Also Check What is POM in Selenium ?

Explicit Wait():

These are confined to a particular web element. Here, you can define a wait() for a certain condition before it proceeds further. And this Explicit wait is of two types ():

a)Web Driver Wait()

b)Fluent Wait()

a)Web Driver Wait():

This wait() is applied to a certain element with the expected condition and time. Moreover, it is applied to a certain element. Besides, it allows throws an expectation, when the element is not found.

The Explicit wait contains the following expected conditions

  1. titleIs()
  2. titleContains()
  3. alertIspresent()
  4. elementSelectionStateToBe()
  5. elementToBeClickable()
  6. elementToBeSelected()
  7. InvisibilityOfElementLocated()
  8. InvisibilityOfElementWithText()
  9. presenceOfAllElementsLocatedBy()
  10. presenceOfElementLocated()
  11. frameToBeAvailableAndSwitchToIt()
  12. visibilityOf()
  13. visibilityOfAllElements()
  14. visibilityOfAllElementsLocatedBy()
  15. visiilityOfElementLocated()
  16. textToBePresentInElement()
  17. textToBePresentInElementLocated()
  18. textToBePresentInElementValue()

Enroll for the free demo today for the real time training on Selenium Online Training

FluentWait():

It defines the maximum amount of time,to wait for a specific condition and frequency. This usually check the condition before throwing the ElementNotVisibleException  exception.  In simple words , it tries to find the web element repeatedly at regular intervals until time (or) object found. We mainly use this command , if the web elements is visible for few seconds especially in Ajax Applications.  The syntax of this method is shown below

Syntax:

Wait wait = new FluentWait(WebDriver reference).withTimeout(timeout, SECONDS).pollingEvery(timeout, SECONDS).ignoring(Exception.class);

WebElement foo=wait.until(new Function<WebDriver, WebElement>() { public WebElement applyy(WebDriver driver) { return driver.findElement(By.id("foo")); } });

This FluentWait() has two paramters namely timeoutvalue and polling frequency.

Consider the example shown below

Wait wait = new FluentWait<WebDriver>(driver).withTimeout(45, TimeUnit.SECONDS).pollingevery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);

In the above example maximum waiting time is 45 seconds. And  the frequency is 5 seconds to check the sucess (or) failure of the specific condition.

Practice the below code in your IDE to execute the fluentWait()

package Seleniumtutorial;

import org.testng.annotations.Test; import java.util.NoSuchElementException; // Include functions import java.util.concurrent.TimeUnit; import java.util.function.Function; //launch Selenium package import org.openqa.selenium.By; import org.openqa.selenium.WebElement; // import drivers import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebDriver; // lanch Exception classes import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; // launch UI waits import org.openqa.selenium.support.ui.Wait; import org.openqa.selenium.support.ui.WebDriverWait; //Launch Test import org.testng.annotations.Test;

public class AppTest3 { protected WebDriver driver; @Test public void onlineitgurututorials() throws InterruptedException { System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" ); String eTitle = "Selenium tutorial | OnlineITGuru"; String aTitle = "" ; driver = new ChromeDriver(); // launch Chrome and redirect it to the Base URL driver.get("https://onlineitguru.com/onlinetutorials/selenium" ); //Maximizes the browser window driver.manage().window().maximize() ; //get the actual value of the title aTitle = driver.getTitle(); //compare the actual title with the expected title if (aTitle.contentEquals(eTitle)) { System.out.println( "Test Passed") ; } else { System.out.println( "Test Failed" ); }

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(30, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class); WebElement clickseleniumlink = wait.until(new Function<WebDriver, WebElement>(){

public WebElement apply(WebDriver driver ) { return driver.findElement(By.xpath("/html/body/div[1]/section/div[2]/div/div[1]/div/div[1]/div/div/div/div[2]/div[2]/div/div/div/div/div[1]/div/div/a/i")); } }); //click on the selenium link clickseleniumlink.click(); //close~ browser driver.close() ; } }

Conclusion:

So till here, we have successfully completed basic Selenium tutorial. Follow our Blog for the best on different technologies in addition to the selenium. Also, don't forgot to subscribe the blog to get the latest articles on your Gadgets. Hope you enjoyed and gained subject on Selenium. And if you are interested to learn more through real-time training enroll now today for the free demo session

Why Choose Us

Master Your Future with OnlineITGuru

We don't just provide courses; we build careers. From expert-led live training to dedicated placement support, discover why thousands of professionals trust us for their digital transformation journey.

200+

Partner Companies

$120K

Highest Package

75%

Average Hike

98%

Placement Rate

Reliable Career Partners

Google
Microsoft
Amazon
Meta
Netflix
Apple