Search

Monday, January 12, 2015

How To Get X Y Coordinates Of Element In Selenium WebDriver

Any web element has Its own position on page and generally It Is measured In x and y pixels and known as x y coordinates of element. x pixels means horizontal position on page from left side and y pixels means vertical position on page from top side. You can find x y coordinates of any element
very easily using some tool. In min time, You can view more related tutorials on THIS PAGE.

In selenium webdriver, You can get x y coordinates of element using Point class. I have created simple example to demonstrate you how to get x y coordinates of any Image on page. We will learn how to get element size In next post.

package Testing_Pack;

import java.util.concurrent.TimeUnit;
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;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class xyCoordinates {
WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/09/selectable.html");
}

@Test
public void getCoordinates() throws Exception {
//Locate element for which you wants to retrieve x y coordinates.
WebElement Image = driver.findElement(By.xpath("//img[@border='0']"));

//Used points class to get x and y coordinates of element.
Point point = Image.getLocation();
int xcord = point.getX();
System.out.println("Element's Position from left side Is "+xcord +" pixels.");
int ycord = point.getY();
System.out.println("Element's Position from top side Is "+ycord +" pixels.");
}
}

When you run above example In eclipse, It will print bellow given result In console.
Element's Position from left side Is 76 pixels.
Element's Position from top side Is 740 pixels.

This way you can find x y coordinates of any element In selenium test and use It whenever required. This thing can help you to perform pixel to pixel testing using selenium webdriver.

We can use  X Y Coordinates Of Element to capture element's screen shot as described In THIS POST.

No comments:

Post a Comment