Monday, August 11, 2014

How to use implicit and explicit wait in Selenium Webdriver

In Selenium webdriver, we need to wait for sometimes to load the page or any element of a page. In that cases we can use wait.
There are two types of wait used in selenium webdriver.
  1. Implicit Wait
  2. Explicit wait
How to implement implicit wait
We can instruct the browser to wait up to a certain amount of time before throwing a not element found exception. When the page or a component of a page is loaded, it waits up to the time that is declared at the implicit wait command. If the page or component is not loaded with in this time period, then selenium Webdriver throws an exception that the specific element is not found. Declaring wait command for a webdriver object will stay up to its life time until the driver is closed.

driver.manage().timeouts().implicitlyWait(time period, TimeUnit.SECONDS);

time period : Here time value is given as input. How many seconds the driver has to wait is given here.
TimeUnit.SECONDS : Time period is measured as second here. You can use other time unit like day, hour etc.

Example (Java) :
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

Implicit wait can make executing scripts slower.

How to implement Explicit wait
Explicit wait is used to define wait command for a single component load or single condition execution. It only waits for the single component load or single lines execution. There are two classes WebDriverWait and ExpectedConditions for this purpose.

WebDriverWait wait = new WebDriverWait(driver, time period);
wait.until(ExpectedConditions.textToBePresentInElement(By.xpath(getTxtVerifyTitle()), Text Title));

time period : Here time value is given as input. How many seconds the driver has to wait is given here.

Example (Java) :
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.textToBePresentInElement(By.xpath(getTxtVerifyTitle()), "Verify Email"));

ExpectedConditions class has some conditions.

alertIsPresent() : Is Alert Present?
elementSelectionStateToBe: Is the element selected?
elementToBeClickable: Is the element clickable?
elementToBeSelected: Element is selected
frameToBeAvailableAndSwitchToIt: Is frame available and selected?
invisibilityOfElementLocated: Is the element invisible?
presenceOfAllElementsLocatedBy: All elements presence location.
refreshed: Wait for a page refresh.
textToBePresentInElement: Is the text present for a particular element?
textToBePresentInElementValue: Is the element value present for a particular element?
visibilityOf: Is the element visible?
titleContains: Is that title contain?