Get Position/Coordinates of Web Element
To get the position or coordinates of a web element using Selenium in Java, call getLocation()
on the Web Element object.
The following is a simple code snippet to get the position/coordinates of web element element
.
element.getLocation()
getLocation()
returns a Point object which represents the position of calling web element, from the left (X-coordinate) and top (Y-coordinate) of the rendered web page respectively.
Example
In the following program, we write Selenium Java code to visit WikiPedia Main Page, find the web element with the id "Welcome_to_Wikipedia"
, then get the location/position/coordinates of this web element.
Java Program
import org.openqa.selenium.By; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class MyAppTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://en.wikipedia.org/wiki/Main_Page"); WebElement element = driver.findElement(By.id("Welcome_to_Wikipedia")); Point location = element.getLocation(); System.out.println("X, Y - coordinates : " + location); driver.quit(); } }
Output
X, Y - coordinates : (565, 652)
We can also access the individual X-coordinate an Y-coordinate via Point object’s getX() and getY() methods.
We shall modify the program, to print the X-coordinate and Y-coordinate separately.
Java Program
import org.openqa.selenium.By; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class MyAppTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://en.wikipedia.org/wiki/Main_Page"); WebElement element = driver.findElement(By.id("Welcome_to_Wikipedia")); Point location = element.getLocation(); System.out.println("X : " + location.getX()); System.out.println("Y : " + location.getY()); driver.quit(); } }
Output
X : 565 Y : 652