简体   繁体   English

将 Robot Framework xPath 转换为 Selenium Python 等效项。

[英]Convert Robot Framework xPath to Selenium Python equivalent.

I am trying to convert xpath in robot to python code.我正在尝试将机器人中的 xpath 转换为 python 代码。 I wanted the below xpath in Robot to be converted to python code我希望将 Robot 中的以下 xpath 转换为 python 代码

This works in Robot:这适用于机器人:

xpath=(//th[@class="picker-switch"])[2]

I have tried in python我在 python 中尝试过

self._driver.find_element_by_xpath("//th[@class='picker-switch'][2]")

Which resulted in the following error:这导致了以下错误:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//th[@class='datepicker-switch'][2]"}

and

self._driver.find_element_by_xpath("//th[@class='picker-switch']")[2]

That caused:这导致:

'WebElement' object does not support indexing

当我用括号(...)将 xpath 语句括起来时,它开始工作:

self._driver.find_element_by_xpath("(//th[@class='picker-switch'])[2]").click()

It failed, as what you have put in the first python attempt was not the same xpath as in RF ;).它失败了,因为您在第一次 Python 尝试中所使用的 xpath 与 RF 中的 xpath 不同;)。

In the original xpath the expression is surrounded with brackets (expression) , and then the index.在原始 xpath 中,表达式用括号(expression)包围,然后是索引。 Which reads - find all elements matching the expression, and return the second one.其中读取 - 找到与表达式匹配的所有元素,并返回第二个。

Without the brackets it is - find all th with that class, which are the 2nd child of their parents element - quite different :)没有括号 - 找到该类的所有th ,它们是其父元素的第二个子元素 - 完全不同:)

For the record, the corrected second python attempt should be作为记录,更正的第二次 python 尝试应该是

self._driver.find_elements_by_xpath("//th[@class='picker-switch']")[1]

find_elements_by_xpath will return all elements matching the expression as a list, and [1] will return the 2nd element in that list - python's lists are zero-based (start from index 0), while xpath's - one-based.find_elements_by_xpath将返回与表达式匹配的所有元素作为列表, [1]将返回该列表中的第二个元素 - python 的列表从零开始(从索引 0 开始),而 xpath 的 - 从一开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM