Java 如何使用 Webdriver Selenium 获取“style”元素的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18452790/
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-12 01:43:44  来源:igfitidea点击:

How to Using Webdriver Selenium to get the value of "style" element

javaselenium

提问by Sohaib Maroof

I want to check whether the value of a style element is greater than a particular value (i.e., is left > 666px ?), but I am unable to get ahold of the value.

我想检查样式元素的值是否大于特定值(即,是否为 left > 666px ?),但我无法获得该值。

Here is the HTML code of the style that I want to capture:

这是我要捕获的样式的 HTML 代码:

<pre><span id="da2c" style="left: 666px; top: 27px;"></pre>

I am using this code to try to print its value, but it's not printing:

我正在使用此代码尝试打印其值,但未打印:

System.out.print(driver.findElement(By.id("da1c")).findElement(By.cssSelector("span")).getAttribute("style"));

I want something like this:

我想要这样的东西:

if ((driver.findElement(By.id("da1c")).findElement(By.cssSelector("span")).getAttribute("style")).value> 700) {
  System.out.println("value exceeding")
}

回答by ddavison

If you execute .getAttribute("style")on that span, you will recieve a String.

如果您.getAttribute("style")在该跨度上执行,您将收到一个字符串。

left: 666px; top: 27px;
You can use string manipulation to fetch a particular style.

left: 666px; top: 27px;
您可以使用字符串操作来获取特定样式。

Alternatively, you can execute some javascript magic using the JavaScriptExecutor, and fetching the leftvalue directly by

或者,您可以使用 JavaScriptExecutor 执行一些 javascript 魔术,并left直接通过

String script = "var thing = window.document.getElementById('da2c'); 
                             window.document.defaultView.getComputedStyle(thing, null).getPropertyValue('left');";

and then check it from there.

然后从那里检查它。

回答by Anirudh

You may capture the Computed Css value as shown in the firebug screenshot below:

您可以捕获 Computed Css 值,如下面的萤火虫屏幕截图所示:

enter image description here

在此处输入图片说明

like this:

像这样:

WebDriver web = new FirefoxDriver(;
String visibility = web.findElement(By.xpath("//your xpath")).getCssValue("display");

回答by Максим Скрипченко

driver.findElement(By.locator( yourLocator )).getAttribute( requiredAttribute )

It will return String

它将返回字符串