为什么 Selenium 给我一个不区分大小写的 Style 属性?

Why is Selenium is giving me a case insensitive Style attribute?

我正在尝试从以下项目中获取 "Style" 属性:

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

但是当我使用以下命令时:

driver.find_element_by_xpath("//a[@tabindex='"+str(m)+"']/../../following-sibling::td[2]").get_attribute('style')

Selenium 给我:

'background-color: transparent; min-width: 19.14mm; width: 21.26mm;'

而不是

'background-color:Transparent;min-width: 19.14mm;WIDTH:21.26mm;'

style 属性是一个特殊属性,因为它的内容必须符合 HTML 文档规范,但也必须符合 CSS 文档规范。 HTML doc specs 表示样式标签:

The value of the style attribute must match the syntax of the contents of a CSS declaration block (excluding the delimiting braces)

在您阅读 CSS doc specs 之前,这不是很有帮助,其中声明:

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.

知道了这一点,我们可以得出结论,就 CSS 规范而言,width=WIDTH。问题仍然是为什么 selenium 将属性小写。好吧,原来获取元素的 CSS 是 special casegetAttribute。使用常规 getAttribute 并没有真正检查任何内容,并且原始字符串值是 returned。然而,对于 CSS 的特殊情况,有一个额外的步骤来获取计算值,而不是原始值。这是确切的措辞:

  1. 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)

所以你可以看到 style 属性实际上并不是直接来自原始文本值,而是来自计算值,这可能是小写的一切,只是因为它无关紧要,而且因为 CSS 属性通常是小写的。这也很明显,因为在您的 returned 文本中也插入了空格(提示它正在被解析和重新输出)。最后,如果您在样式标签中放入无效的 CSS 属性,getAttribute 根本不会 return 它在字符串中!

如果您需要原样的值,我通过最近的实验了解到 getAttribute 的 javascript 版本不会修改字符串文本,因此我建议使用驱动程序的 execute_script 获取方法。

如果您的用例是检索 style 属性,理想情况下您需要使用 value_of_css_property(property_name) 方法而不是使用 get_attribute()。所以你的有效代码块将是:

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@tabindex='"+str(m)+"']/../../following-sibling::td[2]"))).value_of_css_property("style"))

参考

您可以在以下位置找到一些相关讨论:

  • How can I verify text is bold using selenium on an angular website with C#