如果这是经常重复的事情,并且您想集中逻辑并且根本不必处理变量,那么Custom Locator Strategy,
受您的问题启发的示例:
*** Test Cases ***
Test Case
Add Location Strategy table Custom Locator Strategy
Page Should Contain Element table=3
*** Keywords ***
Custom Locator Strategy
[Arguments] ${browser} ${criteria} ${tag} ${constraints}
${element}= Get Webelement css=.tr > td:nth-child(${criteria})
[Return] ${element}
这将适用于所有将定位器作为输入参数的关键字。自定义定位器策略只需要返回一个 Web 元素。
在我看来满足内联标准但在我看来不是更具可读性的替代方法(留给读者)是使用字符串对象函数。它们在机器人框架指南的Advanced Variable Syntax 部分及其周围进行了描述:
*** Variables ***
${locator_template} css=.tr > td:nth-child(%)
*** Test Cases ***
TC
Log Locator Template: "${locator_template}"
${locator} Set Variable ${locator_template.replace("%", "9")}
Log Locator Variable: "${locator}"
Log Inline Variable: "${locator_template.replace("%", "9")}"
Log Locator Template: "${locator_template}"
这个例子展示了如何使用内联对象函数。由于 Python String 对象具有方法 replace,它将提供一种替换相同变量的稳定方法,并使用它的替换输出来进一步分配关键字。
它将产生以下结果:
Starting test: Robot.String Replace.TC
20180513 12:25:21.057 : INFO : Locator Template: "css=.tr > td:nth-child(%)
20180513 12:25:21.058 : INFO : ${locator} = css=.tr > td:nth-child(9)
20180513 12:25:21.059 : INFO : Locator Variable: "css=.tr > td:nth-child(9)"
20180513 12:25:21.060 : INFO : Inline Variable: "css=.tr > td:nth-child(9)"
20180513 12:25:21.061 : INFO : Locator Template: "css=.tr > td:nth-child(%)"
Ending test: Robot.String Replace.TC
如您所知,replace 函数返回结果,并且不更新原始字符串。这使得它可以用作可重用模板。