Java 使用 Selenium 网络驱动程序获取元素的绝对位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21461347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:50:31  来源:igfitidea点击:

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

javajavascriptdomselenium-webdriver

提问by barak manos

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

我在 Java 中使用 Selenium 网络服务器,以便自动化许多网页。

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?

我怎样才能获得 的绝对位置element

In Javascript, I can get the offsetTopand offsetLeftvalues of any element in the DOM:

在 Javascript 中,我可以获取DOM 中任何元素的offsetTopoffsetLeft值:

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.

所以首先想到的是用JavascriptExecutor.

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

但我想避免这种情况。有没有其他方法可以用 Selenium 获得这些值?

Thanks

谢谢

回答by Martin

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

您是否尝试过使用 的getLocation()方法WebElement?似乎做你需要的......

Here's the API doc for that:

这是 API 文档:

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

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

但是,根据您网站的构建方式,元素位置可能取决于窗口的大小(检查style="position:fixed"),因此在尝试验证位置时要小心...

回答by ficoath

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

在 Python 中,这将获得 web 元素的顶部偏移量:

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):

由于两者都使用 Selenium,那么在 Java 中等效的将是(未经测试):

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