Friday 22 July 2016

Selenium: WebDriver: implicit wait

WebDriver interface provides implicitlyWait method, by using this method you can specify the amount of time the driver should wait when searching for an element if it is not immediately present. Methods findElement, findElements are affected by implicit wait. findElement method return as soon as it finds an element (or) timeout is reached. findElments method return as soon as there are more than 0 items in the found collection, or will return an empty list if the timeout is reached. Following is the signature of implicitlyWait method.

Timeouts implicitlyWait(long time, TimeUnit unit);

Following statement sets the time out to 10 seconds.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Following is the complete working application. Assuem index.jsp is available at http://localhost:8080/application/.


index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>

<body>
 <div class="center">
  <h1>Simple application to demonstrate Selenium webdriver</h1>
 </div>

 <div class="center">
  <p>WebDriver interface provides number of methods to locate
   elements in a web page. You can locate an element by using class
   name, id, name, linktext etc.,</p>

  <p>Some times there may be multiple web elements that match given
   criteria, in those situations you can use findElements method.</p>
 </div>
</body>
</html>

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class App {
 public static void main(String[] args) {
  WebDriver driver = new FirefoxDriver();
  driver.get("http://localhost:8080/application");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

  List<WebElement> webElements = driver.findElements(By.tagName("p"));

  for (WebElement element : webElements) {
   System.out.println("*******************");
   System.out.println(element.getText() + "\n");
  }

  driver.close();
 }
}


Output
*******************
WebDriver interface provides number of methods to locate elements in a web page. You can locate an element by using class name, id, name, linktext etc.,

*******************
Some times there may be multiple web elements that match given criteria, in those situations you can use findElements method.


Previous                                                 Next                                                 Home

No comments:

Post a Comment