简体   繁体   中英

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

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM