获取Selenium中所选元素的所有CSS属性的值 [英] Getting the values of all the CSS properties of a selected element in Selenium

查看:3355
本文介绍了获取Selenium中所选元素的所有CSS属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经通过其XPath使用以下方式找到一个元素:

Suppose that I have found an element by its XPath using:

WebElement we = driver.findElement(By.xpath ));

我知道我可以通过获取特定CSS属性的值we.getCssValue 一些属性),但是我可以获得所有属性的值,而不必明确提及它们的名称?

I know that I can get the value of a particular CSS property by we.getCssValue("some property"), but can I get the values of all the properties without having to mention their names explicitly?

推荐答案

不幸的是



这是本地Selenium API无法实现的。

Unfortunately

this is not possible with native Selenium API.

您可以使用一些JavaScript支持,使用Seleniums的 JavascriptExecutor.executeScript 功能。

You can use some javascript support, using Seleniums' JavascriptExecutor.executeScript functionality.

必要的js代码可以在这里在这里(由@Mahsum Akbas提议)

The necessary js code can be found here and here(as proposed by @Mahsum Akbas)

现在这里是Java / Selenium代码,将返回一个字符串形式的css-attribute01:value01; css-attribute02:value02;。


请注意,这会在元素上返回全部 css属性。

Now here is the Java/Selenium Code that will return you a string in the form of "css-attribute01:value01; css-attribute02:value02;".

Be aware that this will return ALL css-attributes on the element.

WebElement we = driver.findElement(By.tagName("div"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
String script = "var s = '';" +
                "var o = getComputedStyle(arguments[0]);" +
                "for(var i = 0; i < o.length; i++){" +
                "s+=o[i] + ':' + o.getPropertyValue(o[i])+';';}" + 
                "return s;";

System.out.println(executor.executeScript(script, we));

如果你只对元素的内联样式感兴趣,那么你可以使用@JeffC在注释中指出的nativeSelenium:

If you would be interested in only the inline-styles of the element, then you can use "native" Selenium as pointed out by @JeffC in the comments:

driver.findElement(By.tagName("div")).getAttribute("style")



BUT!:



这将只给出内联样式,而不是所有的css - 应用于元素的样式。如果你同时运行这两个版本并打印结果,你会看到巨大的差异。

BUT!:

This will give you only the "inline styles" and NOT all the css-styles that are applied to an element. If you run both versions after one another and print the results you will see the immense difference.

这篇关于获取Selenium中所选元素的所有CSS属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆