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

标签 python css selenium xpath value-of-css-property

我正在尝试从以下元素获取“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 给了我:

'背景颜色:透明;最小宽度:19.14mm;宽度:21.26mm;'

而不是

'背景颜色:透明;最小宽度:19.14mm;宽度: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 case getAttribute 的。使用常规的 getAttribute 不会真正检查任何内容,并返回原始字符串值。然而,对于 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 属性通常是小写。这也很明显,因为返回的文本中也插入了空格(提示它正在被解析并重新输出)。最后,如果您在样式标记中放置了无效的 CSS 属性,getAttribute 根本不会在字符串中返回它!

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

关于python - 为什么 Selenium 给我一个不区分大小写的 Style 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59324068/

相关文章:

python - `pyyaml` 可以 't parse ` pydantic ` object if ` Typing` 模块被使用

python - 如何检查列表中的当前用户是否投票了某个帖子

python - 如何旋转 Selenium 网络浏览器 IP 地址

css - Selenium Webdriver XPATH 我可以找到包含某些文本的标签,但我无法在标签标签上方获得输入标签复选框

python - 安装 python 模块 ImportError (dlib, imutils) raspberry pi

python - 迭代前序 k-ary 树遍历

css - Material UI - 禁用悬停 :none media queries for all controls (all states)

css - 如何消除列之间的差距?

javascript - 在javascript中将背景图像分配给另一个

python - 在 Python 中使用 Selenium 从某个 div 获取链接