简体   繁体   中英

Find Element by Coordinates in Selenium (WebDriver)

I'm aware how to retrieve the coordinates of a web element in Selenium:

WebElement element = driver.findElement(By.xpath(XPath));
Point location = element.getLocation();
location.x + " " + location.y

However I'm trying to do the opposite - locate a web element using its coordinates.

I understand I could find all elements on a web page, loop through the list of elements, get the x,y coordinates of each element in the list and compare it to the expected coordinates. If both x and y coordinates of an element match the expected web element I could return the given web element. However it seems very inefficient to me to need to loop through every web element on a page to find the one matching element.

Is there a more of a direct way of finding an element by coordinates?

Note: Although a similar question has been asked over here: Get element at specified position - JavaScript - my question is different bec I want to be able to do this directly using Selenium without the need to come onto Javscript.

The only possible way is by checking the coordinates against all possible elements (if you don 't know nothing about the element you are looking for, Eg. the tag)

So use findElements like driver.findElements(By.cssSelector("*")) OR driver.findElements(By.xpath("//*")) then for each of the found elements check if their location x , y is the ones you are trying to match and return the element if any.

OR call the js elementFromPoint trough the driver as described here :)

Using MoveToElement you will be able to find or click in whatever point you want, you have just to define the first parameter, it can be the session(winappdriver) or driver(in other ways) which is created when you instance WindowsDriver. Otherwise you can set as first parameter a grid (my case), a list, a panel or whatever you want.

Note: The top-left of your first parameter element will be the position X = 0 and Y = 0

Actions actions = new Actions(this.session);
int xPosition = this.session.FindElementsByAccessibilityId("GraphicView")[0].Size.Width - 530;
int yPosition = this.session.FindElementsByAccessibilityId("GraphicView")[0].Size.Height- 150;
actions.MoveToElement(this.xecuteClientSession.FindElementsByAccessibilityId("GraphicView")[0], xPosition, yPosition).ContextClick().Build().Perform();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM