通过 xpath 查询获取属性在浏览器中成功,但在 Robot Framework 中失败
-
21-12-2019 - |
题
我有一个特定的 XPATH 查询,我用它来获取某个 HTML 元素的高度,当我通过 XPath Helper 插件在 Chrome 中执行它时,它会完美地返回所需的值。
//*/div[@class="BarChart"]/*[name()="svg"]/*[name()="svg"]/*[name()="g"]/*[name()="rect" and @class="bar bar1"]/@height
但是,当我通过机器人框架中的获取元素属性关键字使用相同的查询时
Get Element Attribute//*/div[@class="BarChart"]/*[name()="svg"]/*[name()="svg"]/*[name()="g"]/*[name()="rect" and @class="bar bar1"]/@height
...然后我收到了关于此 XPATH 的 InvalidSelectorException 异常。
InvalidSelectorException: Message: u'invalid selector: Unable to locate an
element with the xpath expression `//*/div[@class="BarChart"]/*[name()="svg"]/*
[name()="svg"]/*[name()="g"]/*[name()="rect" and @class="bar bar1"]/`
因此,Robot Framework 或 Selenium 删除了 @ 符号及其后面的所有内容。我认为这是一个转义问题,并在@height之前添加和删除了一些斜杠,但不成功。我还尝试将此查询的结果封装在 string() 命令中,但这也不成功。
有人有办法防止我的 XPATH 查询被破坏吗?
解决方案
看起来您在使用机器人时不能在XPath本身中包含属性轴。您需要按XPath检索元素,然后在此外指定属性名称。看起来语法是这样的:
Get Element Attribute xpath=(//*/div[@class="BarChart"]/*[name()="svg"]/*[name()="svg"]/*[name()="g"]/*[name()="rect" and @class="bar bar1"])@height
.
或或许(我从未使用过机器人):
Get Element Attribute xpath=(//*/div[@class="BarChart"]/*[name()="svg"]/*[name()="svg"]/*[name()="g"]/*[name()="rect" and @class="bar bar1"])[1]@height
.
本文档说
attribute_locator由元素定位器组成,后跟@符号和属性名称,例如“emplex_id @ class”。
所以我认为我在上面发布的是正确的轨道。
其他提示
您的观察是正确的,关键字似乎会删除最终之后的所有内容 @
. 。更正确的是,它使用 @
将元素定位器与属性名称分开,并通过在最后一个字符串拆分字符串来实现这一点 @
特点。
再多的转义也无法解决问题,因为代码此时没有进行任何解析。这是执行该操作的确切代码(截至撰写本文时...):
def _parse_attribute_locator(self, attribute_locator):
parts = attribute_locator.rpartition('@')
...
简单的解决方案是删除尾部斜杠,因此您的 xpath 将如下所示:
//*/div[@class="BarChart"]/... and @class="bar bar1"]@height`
不隶属于 StackOverflow