Is it possible to either run or get the same functionality provided by document.elementFromPoint
using a Selenium webdriver?
Asked
Active
Viewed 3,556 times
7

SiKing
- 10,003
- 10
- 39
- 90

Andrey Fedorov
- 9,148
- 20
- 67
- 99
1 Answers
14
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.

Louis
- 146,715
- 28
- 274
- 320
-
Thanks, that makes a lot of sense! If anyone knows of a way to do it without reaching into the JS on the page, that would be preferred, but this will work, as well. – Andrey Fedorov May 05 '15 at 21:06
-
With JavaScript this will only work if you have no frame or iframe on the page. Otherwise cross site scripting protection in the browser prohibits accessing another frame in JavaScript. The correct solution would be to implement this in the driver. – Elmue Sep 10 '15 at 15:46
-
@Elmue I've just tried it in Chrome, on a page that loads another site in an `iframe`. It works. – Louis Sep 10 '15 at 15:57
-
It is much more complicated if you want to respect also frames and iframes. I posted a working code in C# that you find here: http://stackoverflow.com/questions/31910534/executing-javascript-elementfrompoint-through-selenium-driver/32574543#32574543 – Elmue Sep 14 '15 at 22:03