Thursday 11 August 2016

Selenium2: WebDriver: getLocation: Get location of the element

WebElement interface provides getLocation method, which returns a
Point instance, containing the location of the top left-hand corner of the 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 class="center">
  <h1 id="header1">Simple application to demonstrate Selenium
   webdriver</h1>
 </div>

 <div class="center">
  <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 gets the location of h1, p elements.
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
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 header = driver.findElement(By.tagName("h1"));
  WebElement paragraph = driver.findElement(By.tagName("p"));

  Point headerLocation = header.getLocation();
  Point paragraphLocation = paragraph.getLocation();

  System.out.println("h1 tag location is " + headerLocation);
  System.out.println("p tag location is " + paragraphLocation);

  driver.close();
 }
}


Output
h1 tag location is (8, 21)
p tag location is (8, 81)



Previous                                                 Next                                                 Home

No comments:

Post a Comment