Reputation: 77
I am using Selenium WebDriver and coding in Java. In a code I need to scroll down to a specific element in the web page for clicking it. I am using JavascriptExecutor command. My question is how will I get to know the exact x and y coordinates of that specific element as per the position of it in the web page. The syntax of the code I am using is given below:
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("scroll(x,y)");
In the second line of the above code I need to give the specific values for the x and y coordinates of the element I want to click.
Upvotes: 4
Views: 46461
Reputation: 193388
To know the exact x
and y
coordinates of that specific element as per the pixel position of it in the web page you can consider to use the following code block:
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 location_of_element
{
public static void main(String[] args)
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in");
WebElement element = driver.findElement(By.name("q"));
Point point = element.getLocation();
System.out.println("Element's Position from left side is: "+point.getX()+" pixels.");
System.out.println("Element's Position from top is: "+point.getY()+" pixels.");
}
}
Ensure that you have imported
org.openqa.selenium.Point
The output on your console will be as:
Element's Position from left side is: 413 pixels.
Element's Position from top is: 322 pixels.
Upvotes: 4
Reputation: 5347
You can get coordinates using java selenium,
webElement.getLocation().getX();
webElement.getLocation().getY();
Upvotes: 2
Reputation: 17603
Santosh is right you should scroll using reference of element. but if still you want to get the coordinates use below code:-
You can use below code:-
@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 classname = Image.getLocation();
int xcordi = classname.getX();
System.out.println("Element's Position from left side"+xcordi +" pixels.");
int ycordi = classname.getY();
System.out.println("Element's Position from top"+ycordi +" pixels.");
}
source :-
http://www.maisasolutions.com/blog/How-o-get-X-Y-coordinates-of-element-in-Selenium-WebDriver
Upvotes: 0
Reputation: 2019
I suggest you to give reference the element itself instead of its coordinates.
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
Hope this helps. Thanks.
Upvotes: 3