7

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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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 I've just tried it in Chrome, on a page that loads another site in an iframe. It works.
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: stackoverflow.com/questions/31910534/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.