Implicit Wait in Serenity

HOME

Most Web applications are asynchronous by nature. So it has become necessary to wait for elements, before trying to interact with them. This can be achieved by the use of wait functionality.

I won’t recommend the use of Thread.sleep() statement to wait for a specific web element in the web page, as it slows down the execution as well as makes the test brittle. If you are using Serenity and Selenium for tests, then there are various default timeouts – Implicit, Explicit, and Fluent Wait.

What is Implicit Wait?

Implicit Waits are used to ensure that Serenity does not fail a test if a web element is not immediately present on the page when you first try to use it. Using Implicit wait, you can search for the web element for the specified amount of time. If still, the web element is not found, then Serenity throws NoSuchElementException exception.

To use ImplicitWait in the Test, mention the below-mentioned statement in serenity.properties.

webdriver.timeouts.implicitlywait

There is another way to add implicitwait. Add it to the serenity.conf file as shown below:-

webdriver {
    timeouts {
        implicitlywait = 5000
     }
}

Note:- Make sure to add webdriver and timeout in the same file, either both to properties file or both to conf files.

Let me explain the use of Implicit Wait. Below I have created two classes – ImplictWaitDemo and SynchronizationTests.

ImplictWaitDemo contains detail like default URL, XPath of web elements, methods containing the code for the test whereas SynchronizationTests class calls the tests defined in ImplictWaitDemo and run them using Serenity Runner (@RunWith(SerenityRunner.class)

Scenario 1 – The default value in Serenity for Implicit Wait is currently 2 seconds. In the below example, I’ll open a web page and will try to assert the text present in the webpage. Serenity will wait for 2 seconds and the web element will not be found in 2 secs, so the test fails.

ImplictWaitDemo

@DefaultUrl("http://the-internet.herokuapp.com/dynamic_loading/1")
public class ImplictWaitDemo extends PageObject {

	@FindBy(xpath = "//*[@id='start']/button")
	WebElementFacade startButton;

	@FindBy(xpath = "//*[@id='finish']/h4")
	WebElementFacade pageText;

	public void implictWaitDemo1() throws InterruptedException {
		open();

		startButton.click();
		Assert.assertEquals("Hello World!", pageText.getText())
	}
}

SynchronizationTests

@RunWith(SerenityRunner.class)
public class SynchronizationTests {

	ImplictWaitDemo demo;

	@Managed
	WebDriver driver;

	@Test
	public void waitTest1() throws InterruptedException {
		demo.implictWaitDemo1();

	}
}

This shows that Serenity waited for 2 sec for the text – Hello World.

Now, let us add Implicit Wait to the Test. I have added the implicitWait for 5 sec to each step.

webdriver {
    driver = firefox
    timeouts {
        implicitlywait = 5000
     }
}

Now, the Test is successful.

To know the value of wait in the code, you can use the below code. It will show the value of implicit wait in seconds or milliseconds.

System.out.println("Implicit Time defined for the test (in seconds):" + getImplicitWaitTimeout().toSeconds());
System.out.println("Implicit Time defined for the test (in milliseconds):" + getImplicitWaitTimeout().toMillis());

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Advertisement

Selenium Interview Questions and Answers for 2021

HOME

1. What are the different types of locators in Selenium?

Locator is unique address of any web element on web page. Locating elements in WebDriver is done by using the method “findElement(By.locator())”. 
Here, locator() part will be replaced with locator names, like

driver.findElement(By.id(“email”)) 
Types of Locators in Selenium

  • ID
  • ClassName
  • Name
  • TagName
  • LinkText
  • PartialLinkText
  • Xpath – Absolute Path & Relative Path
  • CSS Selector

For more details, click here

 
2. What is an XPath?

XPath is used to locate a web element based on its XML path. The fundamental behind locating elements using XPath is the traversing between various elements across the entire page and thus enabling a user to find an element with the reference of another element 
Various functions used in XPath are:-
1) text()
2) contains()
3) last()
4) AND , OR
5) position()
6) following()
7) preceding()

For more details, click here

3. What is the difference between “/” and “//” in XPath?

Single Slash “/” – Single slash is used to create XPath with absolute path i.e. the XPath would be created to start selection from the document node/start node. Example is given below 

driver.findElement(By.xpath("//*[@id='yDmH0d']/div/div[2]/div[2]/form/content/section/div/content/div/input")

Double Slash “//” – Double slash is used to create XPath with relative path i.e. the XPath would be created to start selection from anywhere within the document. Example is given below

driver.findElement(By.id("email"))

For more details, click here

4. How do we can launch the browser using WebDriver?

Firstly, we should instantiate a Chrome/Chromium session by doing the following

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
           WebDriver driver = newChromeDriver();

Set the path to the chromedriver executable

System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Automation\\Drivers\\chromedriver_win32\\chromedriver.exe");

The chromedriver is implemented as a WebDriver remote server that instructs the browser what to do by exposing Chrome’s internal automation proxy interface.

Firefox

Similarly, we can launch other browsers too like Firefox, InternetExplorer, Edge

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.Firefox.FirefoxDriver;
System.setProperty("webdriver.gecko.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\geckodriver-v0.26.0-win64\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();

MicroSoftEdge

     import org.openqa.selenium.WebDriver;
     import org.openqa.selenium.edge.EdgeDriver;
 System.setProperty("webdriver.edge.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\edgedriver_win64\\msedgedriver.exe");
          WebDriver driver = new EdgeDriver();

For more details, click here 

5. What are the different types of Drivers available in WebDriver?

The different drivers available in WebDriver are

  • FirefoxDriver
  • InternetExplorerDriver
  • ChromeDriver
  • SafariDriver
  • OperaDriver
  • AndroidDriver
  • IPhoneDriver
  • HtmlUnitDriver

6. Explain the different exceptions in Selenium WebDriver

Exceptions in Selenium are similar to exceptions in other programming languages. The most common exceptions in Selenium are:
1. TimeoutException: This exception is thrown when a command performing an operation does not complete in the  expected time.

2. NoSuchElementException: This exception is thrown when an element with given attributes is not found on the web page. Suppose webdriver is trying to click on XPath – “//*[@id=’yDmH0d’]/div/div[2]/div[2]/form/content” which doesn’t exist on that particular web page, then below exception is displayed – org.openqa.selenium.NoSuchElementException.


3. ElementNotVisibleException: This exception is thrown when the element is present in DOM (Document Object Model), but not visible on the web page.

4. StaleElementException: This exception is thrown when the element is either deleted or no longer attached to the DOM.

7. What are the different types of waits available in WebDriver? or 

How do you achieve synchronization in WebDriver?

There are three types of wait in Selenium WebDriver

 1.   Implicit Wait – The implicit wait will tell to the web driver to wait for certain amount of time before it throws a “NoSuchElementException“. The default setting is 0. Once we set the time, web driver will wait for that time before throwing an exception. Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script.
We need to import java.util.concurrent.TimeUnit to use ImplicitWait.

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

2.    Explicit Wait – An explicit wait is code you define to wait for a certain condition to occur before proceeding further in the code. The explicit wait will tell the web driver to wait for certain conditions like visibilityOfElementLocated and maximum amount of time before throwing NoSuchElementException exception. Unlike Implicit waits, explicit waits are applied for a particular instance only.

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Stats1_totalCount")));

3.  Fluent Wait – Fluent Wait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.

Users may configure the wait to ignore specific types of exceptions whilst waiting, such as  NoSuchElementException when searching for an element on the page.

Fluent Wait commands are mainly used when the web elements which sometimes visible in few seconds and some times take more time than usual. Mainly in Ajax applications. We could set the default pooling period based on the requirement.

Wait wait = new FluentWait(driver)  .withTimeout(Duration.ofSeconds(30))
 .pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);

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

For more details, click here 

8. How to set size of Window in Selenium WebDriver?

First fetch the size of the browser window in pixels by below shown code Dimension

size = driver.manage().window().getSize();
         int width1 = size.getWidth();
         int height1 = size.getHeight();

Now, change the size of window by using

driver.manage().window().setSize(new Dimension(1024, 768)); 

9. How to set position of Window in Selenium?

First fetch the coordinates of the top left coordinate of the browser window by

Point position = driver.manage().window().getPosition();
         int x1 = position.getX();
         int y1 = position.getY();

The window can be moved to the chosen position by

// Move the window to the top left of the primary monitor
driver.manage().window().setPosition(new Point(0, 0));

10. What is the difference between driver.findElement() and driver.findElements() commands?

FindElement – This method locates for the first web element on the current web page matching the criteria mentioned as parameter.  
If the web element is not found, it will throw an exception – NoSuchElementException. 

driver.findElement(By.xpath("Xpath location"));

FindElements – This method locates all the web elements on the current web page matching the criteria mentioned as parameter. 

If not found any WebElement on current page as per given element locator mechanism, it will return empty list.     

findElements (By arg0):List<WebElement

For more details, click here 

11. How to type in a textbox using Selenium?

The user can use sendKeys(“String to be entered”) to enter the string in the textbox. The sendKeys types a key sequence in DOM element even if modifier key sequence is encountered.

Syntax - sendKeys(CharSequence… keysToSend ) : void
Command – driver.findElement(By.xpath("//*[@name = 'email']")).sendKeys("abc123@gmail.com") 

For more details, click here

12. How can we get a text of a web element?

Get command is used to retrieve the inner text of the specified web element. The command doesn’t require any parameter but returns a string value. It is also one of the extensively used commands for verification of messages, labels, errors etc displayed on the web pages. 

String Text = driver.findElement(By.id(“Text”)).getText();

13. How to input text in the text box without calling the sendKeys()?

//Creating the JavascriptExecutor interface object by Type casting                                     JavascriptExecutor js = (JavascriptExecutor)driver;              
//Launching the Site        
driver.get("https://www.google.com/");                      js.executeScript("document.getElementsByName('q')[0].value = 'Selenium Introduction';");

For more details, click here

14. How to read a JavaScript variable in Selenium WebDriver? 

//To initialize the JS object
JavascriptExecutor JS = (JavascriptExecutor) webdriver;
//To get the site title
String title = (String)JS.executeScript("return document.title");
System.out.println("Title of the webpage : " + title);

For more details, click here

15. What is JavaScriptExecutor and in which cases JavaScriptExecutor will help in Selenium automation?

There are some conditions where we cannot handle some problems with WebDriver only, web controls don’t react well against selenium commands. In this kind of situations, we use Javascript. It is useful for custom synchronizations, hide or show the web elements, change values, test flash/HTML5 and so on. 
In order to do these, we can use Selenium’s JavascriptExecutor interface which executes JavaScript through Selenium driver.

It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript(Script,Arguments);

Script – This is the JavaScript that needs to execute.

Arguments – It is the arguments to the script. It’s optional
Let’s see some scenarios we could handle using this Interface:
1. To type Text in Selenium WebDriver without using sendKeys() method 2. To click a Button in Selenium WebDriver using JavaScript
3. To handle Checkbox
4. To generate Alert Pop window in selenium
5. To refresh browser window using Javascript
6. To get innertext of the entire webpage in Selenium
7. To get the Title of our webpage
8. To get the domain
9. To get the URL of a webpage
10. To perform Scroll on an application using  Selenium


For more details, click here

16. How To Highlight Element Using Selenium WebDriver?

By using JavascriptExecutor interface, we could highlight the specified element

//Create the JavascriptExecutor interface object by Type casting               JavascriptExecutor js = (JavascriptExecutor)driver; 

//Higlight element - Total PageCount
WebElement TotalCount = driver.findElement(By.id("Stats1"));js.executeScript("arguments[0].style.border='3px dotted blue'", TotalCount); 

For more details, click here

17. List some scenarios which we cannot automate using Selenium WebDriver?

1. Bitmap comparison is not possible using Selenium WebDriver.
2. Automating Captcha is not possible using Selenium WebDriver.
3. We can not read bar code using Selenium WebDriver.

18. How can you find if an element in displayed on the screen?

WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels etc.

  • isDisplsyed()
  • isSelected()
  • isEnabled()
isDisplayed():
boolean elePresent = driver.findElement(By.xpath("xpath")).isDisplayed();
isSelected():
boolean eleSelected= driver.findElement(By.xpath("xpath")).isSelected(); 
isEnabled():
boolean eleEnabled= driver.findElement(By.xpath("xpath")).isEnabled();

19. Explain how you can switch back from a frame?

To switch back from a frame use method defaultContent()  

driver.switchTo().defaultContent(); 

20. What is the difference between getWindowhandles() and getwindowhandle() ?

getwindowhandles(): It is used to get the address of all the open browser and its return type is Set<String>

getwindowhandle(): It is used to get the address of the current browser where the control is and return type is string.

For more details, click here

21. How to select value in a dropdown?

To perform any operation on DropDown, we need to do 2 things:-

1) Import package org.openqa.selenium.support.ui.Select 
2) Create new Select object of class Select

Select oSelect = new Select());
Different Select Commands
  1. selectByValue
Select yselect = new Select(driver.findElement(By.id("year")));
yselect.selectByValue("1988");

2. selectByVisibleText

 Select mselect = new Select(driver.findElement(By.id("month")));
 mselect.selectByVisibleText("Apr");

3. selectByIndex

Select bselect = new Select(driver.findElement(By.name("birthday_day")));
bselect.selectByIndex(8);

For more details, click here

22. How to switch to a new window (new tab) which opens up after you click on a link?

If you click on a link in a web page and it opens a new window, but WebDriver will not know which window the Operating system consider active. To change the WebDriver’s focus/ reference to the new window we need to use the switchTo() command. driver.switchTo().window();

Here, ‘windowName’ is the name of the window you want to switch your reference to.

In case you do not know the name of the window, then you can use the driver.getWindowHandle() command to get the name of all the windows that were initiated by the WebDriver. Note that it will not return the window names of browser windows which are not initiated by your WebDriver.

Once you have the name of the window, then you can use an enhanced for loop to switch to that window. Look at the piece of code below.

String handle= driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) 
{
driver.switchTo().window(handle); 
}

//Store the ID of the original window
String originalWindow = driver.getWindowHandle();

//Check we don't have other windows open already
 assert driver.getWindowHandles().size() == 1;

 //Click the link which opens in a new window
 driver.findElement(By.linkText("new window")).click();

 //Wait for the new window or tab
 wait.until(numberOfWindowsToBe(2));
  
//Loop through until we find a new window handle
for (String windowHandle : driver.getWindowHandles()) {
    if(!originalWindow.contentEquals(windowHandle)) {
        driver.switchTo().window(windowHandle);
        break; 
    } 
}
  
//Wait for the new tab to finish loading content
wait.until(titleIs("Selenium documentation"));  

For more details, click here

23. How to handle browser (chrome) notifications in Selenium?

In Chrome, we can use ChromeOptions as shown below.

ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
WebDriver player = new ChromeDriver(options);

24. How to delete Browser Cookies with Selenium Web Driver?

driver.Manage().Cookies.DeleteAllCookies();

25. What are the different types of navigation commands?

  • driver.navigate().forward(); – to navigate to the next web page with reference to the browser’s history.
  • driver.navigate().back(); – takes back to the previous webpage with reference to the browser’s history.
  • driver.navigate().refresh(); – to refresh the current web page thereby reloading all the web elements.
  • driver.navigate().to(“url”); – to launch a new web browser window and navigate to the specified URL.

For more details, click here

26. How can we handle Web-based Pop-ups or Alerts in Selenium?

To handle Web-based alerts or popups, we need to do switch to the alert window and call Selenium WebDriver Alert API methods.

  • dismiss(): To click on Cancel button.
  • accept(): To Click on OK button.
  • getText(): To get the text which is present on the Alert.
  • sendKeys(): To enter the text into the alert box.

For more details, click here

27. What are the ways to refresh a browser using Selenium WebDriver?

1. Using driver.navigate().refresh() command.
2. Using driver.get(“URL”) on the current URL or using driver.getCurrentUrl()
3. Using driver.navigate().to(“URL”) on the current URL or driver.navigate().to(driver.getCurrentUrl());
4. Using sendKeys(Keys.F5) on any textbox on the webpage.        

28. What is Page Object Model in Selenium?

Page Object is a Design Pattern which has become popular in test automation for enhancing test maintenance and reducing code duplication. A page object is an object-oriented class that serves as an interface to a page of your AUT. The tests then use the methods of this page object class whenever they need to interact with the UI of that page. The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently all changes to support that new UI are located in one place.
The Page Object Design Pattern provides the following advantages:
There is a clean separation between test code and page specific code such as locators (or their use if you’re using a UI Map) and lay
There is a single repository for the services or operations offered by the page rather than having these services scattered throughout the tests.

For more details, click here

29. What are the different mouse actions that can be performed?

The different mouse events supported in selenium are
1. click(WebElement element)
2. doubleClick(WebElement element)
3. contextClick(WebElement element)
4. mouseDown(WebElement element)
5. mouseUp(WebElement element)
6. mouseMove(WebElement element)
7. mouseMove(WebElement element, long xOffset, long yOffset)

For more details, click here

30Write the code to double click an element in selenium?

Code to double click an element in selenium is mentioned below

Actions action = new Actions(driver);
   WebElement element=driver.findElement(By.id("elementId"));
   action.doubleClick(element).perform();

31. Write the code to right-click an element in selenium?

Code to right-click an element in selenium is mentioned below-

   Actions action = new Actions(driver);
   WebElement element=driver.findElement(By.id("elementId"));
    action.contextClick(element).perform();

32. How to mouse hover an element in selenium?

Code to mouse hover over an element in selenium is mentioned below:-

Actions action = new Actions(driver);
   WebElement element=driver.findElement(By.id("elementId"));
    action.moveToElement(element).perform();

33. How to do drag and drop in Selenium?

Using Action class, drag and drop can be performed in selenium.

    Actions builder = new Actions(driver);
    Action dragAndDrop = builder.clickAndHold(SourceElement).moveToElement(TargetElement).release(TargetElement).build();
    dragAndDrop.perform();

    Or
  // Create object of actions class
      Actions builder = new Actions(driver);
                       
  // Perform drag and drop operation
       builder.dragAndDrop(from, to).build().perform();

For more details,click here

34. How can we capture screenshots in selenium?

Using the getScreenshotAs method of TakesScreenshot interface, we can take the screenshots in selenium.

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg"));

What is Fluent Wait in Selenium WebDriver

In the previous tutorial, we have discussed about Implict and Explicit Wait. In this blob, we will discuss about Fluent Wait. Fluent Wait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.

Users may configure the wait to ignore specific types of exceptions whilst waiting, such as  NoSuchElementException when searching for an element on the page. Fluent Wait commands mainly used when the web elements, which sometimes visible in few seconds and sometimes take more, time than usual. Mainly in Ajax applications. We could set the default-pooling period based on the requirement.

Wait wait = new FluentWait(driver)

  .withTimeout(Duration.ofSeconds(30))
  .pollingEvery(Duration.ofSeconds(5))
  .ignoring(NoSuchElementException.class);

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

Below is an example which shows the use of Fluent Wait in real world
1) Launch new Browser and open https://www.rediff.com/
2) Click on Money Link present at the top center of the page
3) Sensex of different companies like S&P BSE Sensex, Nift 50, etc. appears at the center of the page
4) Don’t use Fluent Wait to find value of element S& BSE Sensex
5) Close the browser

package SeleniumTutorial;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class FluentWaitDemo {
      public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver","C:\\Users\\SingVi04\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
           WebDriver driver= new ChromeDriver();
           driver.manage().window().maximize();
           driver.get("https://www.rediff.com/");    
           driver.findElement(By.xpath("//a[@href ='https://money.rediff.com']")).click();
            
           String Message= driver.findElement(By.xpath("//*[@id='indmarquee']/div[1]/span[2]")).getText();
           System.out.println("Value of S&P BSE Bankex :"+Message);
      driver.quit();
     }
}

Output
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element
{"method":"xpath","selector":"//*[@id='indmarquee']/div[1]/span[2]"}
(Session info: chrome=78.0.3904.108)

Here, we can see that NoSuchElementException found, as the Web Element is dynamic. We need to wait for some time to find the Web Element.
In the below example, will use Fluent Wait to overcome the above stated issue.

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;

import com.google.common.base.Function;
    public classFluentWaitDemo {
          public static void main(String[] args) {
 
System.setProperty("webdriver.chrome.driver","C:\\Users\\SingVi04\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
         WebDriver driver = newChromeDriver();
          driver.manage().window().maximize();
          driver.get("https://www.rediff.com/");
 
          driver.findElement(By.xpath("//a[@href ='https://money.rediff.com']")).click();
           
          //Fluent Wait
          Wait wait = new FluentWait(driver)
                     .withTimeout(Duration.ofSeconds(15))  
                     .pollingEvery(Duration.ofSeconds(1))                           
                     .ignoring(NoSuchElementException.class);
 
                WebElement BSE_Sensex = wait.until(newFunction(){
                  public WebElement apply(WebDriver driver ) 
                  {
                      WebElement BSE_Bankex = driver.findElement(By.xpath("//*[@id='indmarquee']/div[1]/span[2]"));
           return BSE_Bankex;
                 }
          });
 
       String Message = BSE_Sensex.getText();
       System.out.println("Value of S&P BSE Bankex :"+Message);      
      }
}

Output 
Value of S&P BSE Bankex :42,597.43

Here,
Fluent Wait uses two parameters mainly – timeout value and polling frequency. In the above syntax we took time out value as 15 seconds and polling frequency as 2 seconds. The maximum amount of time (15 seconds) to wait for a condition and the frequency (2 seconds) to check the success or failure of a specified condition. 

If the element is located with in this time frame it will perform the operations else it will throw an “ElementNotVisibleException”

Few important points:-

1) NoSuchElementException. class – This class should be imported from org.openqa.selenium. By default Selenium shows 2 packages as shown in the image below.

If NoSuchElementException.class imported from java.util package, then we will see NoSuchElementException as shown below.

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

This is deprecate. So, do not use this syntax. Refer the below image for error

Implicit, Explicit, & Fluent Wait in Selenium WebDriver

HOME

 

In this tutorial, we will see different type of waits we use in Selenium. We will discuss about “Implicit”, “Explicit” and “Fluent” Wait.

Why do we need wait?

Nowadays web applications are developed using Ajax and Javascript, so when we try to identify a web  element on web page, there are the chances that the loading of that element will take some time or network connectivity is very poor result in “NoSuchElementException” exception. These issues can be resolved with the help of wait in Selenium.

Implicit Wait

The implicit wait will tell to the web driver to wait for certain amount of time before it throws a “NoSuchElementException“. The default setting is 0. Once we set the time, web driver will wait for that time before throwing an exception.

Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script.We need to import java.util.concurrent.TimeUnit to use ImplicitWait.

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

Implicit wait will accept 2 parameters, the first parameter will accept the time as an integer value and the second parameter will accept the time measurement in terms of SECONDS, MINUTES, MILISECOND, MICROSECONDS, NANOSECONDS, DAYS, HOURS, etc.

Let me show how to use implicit wait in our program

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class ImplicitWait_Example {
      public static void main(String[] args) {
                      
     System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.24.0-win64\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
                    
      //Implicit Wait
      driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
      driver.get("https://www.facebook.com");
      driver.findElement(By.name("email")).sendKeys("vibhasingh.verma");
          }
}

In the above example, we have waited for 30 sec, before redirecting the web page to the URL explicitly mentioned in the code.


Explicit Wait


An explicit wait is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are convenience methods available to help write code that will only wait as long as required. 

WebDriverWait in combination with ExpectedCondition is one way to do this.

The explicit wait will tell the web driver to wait for certain conditions like visibilityOfElementLocated and maximum amount of time before throwing NoSuchElementException exception.

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Stats1_totalCount")));

Let me explain this with an example

import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
 
public class ExplicitWaitExample {
            public static void main(String[] args) {
                        System.setProperty("webdriver.chrome.driver",
                                           "C:\\Users\\Vibha\\Desktop\\SeleniumKT\\chromedriver_win32\\chromedriver.exe");
                        // Create a new instance of the Firefox driver
                        WebDriver driver = new ChromeDriver();
                        driver.manage().window().maximize();
                        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
                        driver.get("https://configureselenium.blogspot.com/");
 
                        // Click on READ MORE link. New Page is opened
                        driver.findElement(By.linkText("READ MORE")).click();
 
                        // Explicit Wait
                        WebDriverWait wait = new WebDriverWait(driver, 60);
                    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Stats1_totalCount")));
                        String Count = driver.findElement(By.id("Stats1_totalCount")).getText();
                        System.out.println("Count is :" + Count);
                  driver.close();
            }
}

In the above example, we have used Explicit Wait. We are waiting for the web element – Stats1_totalCount for 60 seconds before performing the next operation.

The following are the Expected Conditions that can used in Explicit Wait

  1. alertIsPresent()
  2. elementSelectionStateToBe()
  3. elementToBeClickable()
  4. elementToBeSelected()
  5. frameToBeAvaliableAndSwitchToIt()
  6. invisibilityOfTheElementLocated()
  7. invisibilityOfElementWithText()
  8. presenceOfAllElementsLocatedBy()
  9. presenceOfElementLocated()
  10. textToBePresentInElement()
  11. textToBePresentInElementLocated()
  12. textToBePresentInElementValue()
  13. titleIs()
  14. titleContains()
  15. visibilityOf()
  16. visibilityOfAllElements()
  17. visibilityOfAllElementsLocatedBy()
  18. visibilityOfElementLocated()

Note:-  Do not mix implicit and explicit waits! Doing so can cause unpredictable wait times. For example, setting an implicit wait of 20 seconds and an explicit wait of 35 seconds could cause a timeout to occur after 25 seconds.

Fluent Wait

The Fluent wait will tell the web driver to wait for certain conditions like visibilityOfElementLocated as well as the frequency with which we want to check before throwing NoSuchElementException exception.

To know more about Fluent Wait, please click here