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
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");
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With