Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the absolute position of an element with Selenium web-driver

I am using a Selenium web-server in Java, in order to automate many web pages.

For example:

WebDriver driver = new FirefoxDriver();
driver.get(url);
WebElement element = driver.findElement(By.id("some_id"));

How can I get the absolute position of element?

In Javascript, I can get the offsetTop and offsetLeft values of any element in the DOM:

var element    = document.getElementById("some_id");
var offsetTop  = element.offsetTop;
var offsetLeft = element.offsetLeft;

So the first thing that comes to mind is to call the above script with a JavascriptExecutor.

But I would like to avoid this. Is there any other way to obtain these values with Selenium?

Thanks

like image 304
barak manos Avatar asked Jan 30 '14 15:01

barak manos


2 Answers

In Python this would get the offset top of a web element:

driver = webdriver.Chrome()
driver.get(url)
element = driver.find_element_by_id('some_id')
offset_top = element.get_attribute('offsetTop')

Since both use Selenium then in Java the equivalent would be (untested):

WebDriver driver = new FirefoxDriver();
driver.get(url);
WebElement element = driver.findElement(By.id("some_id"));
int offsetTop = element.getAttribute("offsetTop");
like image 122
ficoath Avatar answered Oct 21 '22 01:10

ficoath


Have you tried using the getLocation() method of WebElement? Seems to do what you need...

Here's the API doc for that:

http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html

However, depending on how your site is built, an elements position could depend on the size of the window (check for style="position:fixed"), so be careful when trying to validate position...

like image 24
Martin Avatar answered Oct 21 '22 00:10

Martin