With Selenium 4, the getRect() introduced to fetch the element position with respect to top left corner of element and the element size instead of using 2 different methods as getLocation() & getSize() to achieve the same [selenium <= 3.x versions].
Prior to selenium 4, you have use
getLocation() to fetch the X & Y axis values
Point p = el.getLocation();
System.out.println(p.x + " " + p.y);
getSize() to fetch the height and width of an element
Dimension d = el.getSize();
System.out.println(d.height + " " + d.width);
Selenium 4 provides Rectangle class to achieve this feature, this class exposes getRect() to get the element position and size.
getRect().x -> X axis value from top left corner of an element
getRect().y -> Y axis value from top left corner of an element
getRect().width & getRect().height – size of an element
Let’s see the code implementation
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class GetRect {
private static WebDriver driver;
@BeforeMethod
void Login() throws InterruptedException {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.get("https://qavbox.github.io/demo/webtable/");
Thread.sleep(2000);
}
@Test
public void ElScreenshot() throws InterruptedException {
WebElement el = driver.findElement(By.id("regform"));
Rectangle rect = el.getRect();
System.out.println("X-Axis - " + rect.x ); //from left top corner of element
System.out.println("Y-Axis - " + rect.y );
System.out.println("Element Width - " + rect.width );
System.out.println("Element Height - " + rect.height );
//OR
System.out.println(rect.getX());
System.out.println(rect.getY());
System.out.println(rect.getWidth());
System.out.println(rect.getHeight());
Thread.sleep(3000);
driver.quit();
}
}
As you can see in above code, we can use the rect.x or rect.getX() to fetch the x axis position, same for y axis, height & width of an element.




