Thursday 11 August 2016

Selenium2: WebDriver: getRect: get location and size of the rendered element

WebElement interface provides getRect method, which returns a Rectage instance. Rectangle class procides getter methods to get the width, height and location of the given web element.


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 id="div1">
  <h1 id="header1">Simple application to demonstrate Selenium
   webdriver</h1>
 </div>

 <div id="div2">
  <p id="para1">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>
 </div>
</body>
</html>


Assume index.jsp is available at “http://localhost:8080/application”. Following application prints the location and size of the web elements with ids header1, para1.
import org.openqa.selenium.By;
import org.openqa.selenium.Rectangle;
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");

  WebElement ele1 = driver.findElement(By.id("header1"));
  WebElement ele2 = driver.findElement(By.id("para1"));
  
  Rectangle rect1 = ele1.getRect();
  Rectangle rect2 = ele2.getRect();
  
  System.out.println("Dimensions of h1 element are :");
  System.out.println("size : (" + rect1.getWidth() + "," + rect1.getHeight() +")");
  System.out.println("Dimension : (" + rect1.getX() + "," + rect1.getY() +")");
  
  System.out.println("\nDimensions of p element are :");
  System.out.println("size : (" + rect2.getWidth() + "," + rect2.getHeight() +")");
  System.out.println("Dimension : (" + rect2.getX() + "," + rect2.getY() +")");
  
  driver.close();
 }
}


Output
Dimensions of h1 element are :
size : (1064,38)
Dimension : (8,21)

Dimensions of p element are :
size : (1064,19)
Dimension : (8,81)




Previous                                                 Next                                                 Home

No comments:

Post a Comment