Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

javascript - Getting the values of all the CSS properties of a selected element in Selenium

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

WebElement we = driver.findElement(By.xpath("some XPath"));

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Unfortunately

this is not possible with native Selenium API.

But using Javascript you can:

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

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

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

You can change the script according to your needs. For example you could return a string that ONLY has all the values without the attributes. Feel free to change and experiment.

Update

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...