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

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

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

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

不幸

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

但是使用Javascript你可以:

您可以使用Selenium的JavascriptExecutor.executeScriptfunction来使用一些javascript支持。

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

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

请注意,这将返回元素上的所有 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)); 

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

更新

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

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

但!:

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

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)