获取Selenium中所选元素的所有CSS属性的值

Mil*_*lad 5 javascript css java selenium xpath

假设我通过XPath找到了一个元素:

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

我知道我可以获得特定CSS属性we.getCssValue("some property")的值,但是我可以获得所有属性的值而不必明确提及它们的名称吗?

drk*_*hng 15

不幸

本机Selenium API无法做到这一点.

但是使用Javascript你可以:

您可以使用Seleniums的JavascriptExecutor.executeScript功能来使用一些javascript支持.

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

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

请注意,这将返回元素上的所有 css属性.

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));
Run Code Online (Sandbox Code Playgroud)

您可以根据需要更改脚本.例如,您可以返回一个字符串,该字符串只包含没有属性的所有值.随意改变和实验.

更新

如果您只对元素的内联样式感兴趣,那么您可以使用@JeffC在评论中指出的"原生"Selenium:

driver.findElement(By.tagName("div")).getAttribute("style")
Run Code Online (Sandbox Code Playgroud)

但!:

这将只提供"内联样式",而不是所有应用于元素的css样式.如果您逐个运行两个版本并打印结果,您将看到巨大的差异.

  • @JeffC with getAttribute("style")你将只获得内联样式的元素,而不是元素上应用的所有css样式!但补充我的答案是一个很好的观点.谢谢. (2认同)
  • 你是对的先生!我没有想到这一点. (2认同)

Roo*_*oor 8

使用上述脚本获取所有计算样式属性的 Python 版本:

from selenium import webdriver
from pprint import pprint
#require geckodriver in the directory where this script runs
driver = webdriver.Firefox()
driver.get('https://stackoverflow.com')

#Set the element object to the inbox messages icon
element = driver.find_element_by_xpath('//a[@title="Recent inbox messages"]')

#Get all of the style properties for this element into a dictionary
styleprops_dict = driver.execute_script('var items = {};'+
                                   'var compsty = getComputedStyle(arguments[0]);'+
                                    'var len = compsty.length;'+
                                    'for (index = 0; index < len; index++)'+
                                    '{items [compsty[index]] = compsty.getPropertyValue(compsty[index])};'+
                                    'return items;', element)
pprint(styleprops_dict)
Run Code Online (Sandbox Code Playgroud)