I'm trying to get the "Style" attribute from the following item:
<td rowspan="31" style="background-color:Transparent;min-width: 19.14mm;WIDTH:21.26mm;" class="Ac165936899664594908cfec8fa25b2a0270c" height="548"><div style="word-wrap:break-word;white-space:pre-wrap;" class="Ac165936899664594908cfec8fa25b2a0270"> XXXXX </div></td>
But when I use the following command:
driver.find_element_by_xpath("//a[@tabindex='"+str(m)+"']/../../following-sibling::td[2]").get_attribute('style')
Selenium is giving me:
'background-color: transparent; min-width: 19.14mm; width: 21.26mm;'
instead of
'background-color:Transparent;min-width: 19.14mm;WIDTH:21.26mm;'
The style
attribute is a special attribute in that its contents must match both the HTML doc specs, but also the CSS doc specs. The HTML doc specs says this of the style tag:
The value of the style attribute must match the syntax of the contents of a CSS declaration block (excluding the delimiting braces)
This isn't too helpful, until you go read the CSS doc specs, which state:
All CSS syntax is case-insensitive within the ASCII range (i.e., [a-z] and [A-Z] are equivalent), except for parts that are not under the control of CSS. For example, the case-sensitivity of values of the HTML attributes "id" and "class", of font names, and of URIs lies outside the scope of this specification. Note in particular that element names are case-insensitive in HTML, but case-sensitive in XML.
Knowing that, we can conclude that as far as the CSS spec is concerned, width
=WIDTH
. The question remains as to why selenium lower-cases the attribute. Well, turns out that getting an element's CSS is a special case of getAttribute
. With the regular getAttribute
nothing is really checked, and the raw string value is returned. With the special case of CSS however, there is an extra step of getting the computed value, rather than the raw value. Here is the exact wording:
- Let computed value be the result of the first matching condition: current browsing context’s document type is not "xml" computed value of parameter property name from element’s style declarations. property name is obtained from url variables. Otherwise "" (empty string)
So you can see that the style attribute isn't actually coming straight from the raw text value, rather from the computed value, which is probably lower-casing everything simply because it doesn't matter, and because CSS attributes are usually lowercase. This is also apparent in that there are inserted spaces in your returned text as well (clue that it's getting parsed and re-output). Finally, if you put an invalid CSS property within your style tag, getAttribute
will not return it in the string at all!
If you need the value as-is, I have learned through recent experimentation that the javascript version of getAttribute
doesn't modify the string text, so I would recommend using the driver's execute_script
method for obtaining that.