Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element at position with Selenium

Is it possible to either run or get the same functionality provided by document.elementFromPoint using a Selenium webdriver?

like image 269
Andrey Fedorov Avatar asked May 04 '15 20:05

Andrey Fedorov


People also ask

How do you get the position of an element in Selenium?

To get the position or coordinates of a web element using Selenium in Java, call getLocation() on the Web Element object.

How do you click on an element at Selenium with coordinates?

We can use the ClickAt command in Selenium IDE. The ClickAt command has two arguments − the element locator and the coordinates which mentions the x and y coordinates of the mouse with respect to the element identified by the locator.

What is the get () method used for in Selenium?

The get command launches a new browser and opens the given URL in your Webdriver. It simply takes the string as your specified URL and opens it for testing purposes. If you are using Selenium IDE, it is similar to open command.

How do you find the coordinates of a WebElement?

To get the unique coordinates of an element we shall create an object of the class Point which shall store the location of the webelement obtained from the getLocation method. Then the individual x and y coordinate values can be computed from the getX and the getY methods respectively.


1 Answers

You have to use JavaScript for that:

element = driver.execute_script("""
return document.elementFromPoint(arguments[0], arguments[1]);
""", x, y)

This assumes that x and y are set to integer values. The arguments you pass to execute_script after the first argument become arguments[0], arguments[1], etc. on the JavaScript side. (This is just the good old arguments object. Selenium wraps the JavaScript code you give to execute_script in a function.) The element will either be an instance of WebElement or None if nothing could be found. According to the MDN page on this function a None value will happen if:

If the specified point is outside the visible bounds of the document or either coordinate is negative, the result is null.

JavaScript null becomes None in Python.

like image 91
Louis Avatar answered Oct 12 '22 03:10

Louis