如何将共用变量的两个SeleniumLibrary关键字封装为自定义关键字并调用
这问题我太熟了!在Robot Framework里把重复的Selenium操作封装成自定义关键字,能大幅简化测试用例的写法,给你两种实用方案:
方法一:用Robot原生语法快速封装(最适合基础场景)
你只需要在测试用例文件或者专门的资源文件(.robot)里,添加*** Keywords ***区块,直接合并两个常用关键字即可:
*** Keywords *** Wait Until Visible And Click [Arguments] ${locator} ${timeout}=${TIMEOUT} # 先等待元素可见,支持自定义超时(默认用全局TIMEOUT变量) Wait Until Element Is Visible ${locator} timeout=${timeout} # 等待完成后点击目标元素 Click Button ${locator}
调用方式
完全符合你期望的写法,还支持自定义超时参数:
*** Test Cases *** Home Page Navigation Test Click Home Button Wait Until Visible And Click ${HOME_BUTTON} # 如果需要更长等待时间(比如20秒),直接传参: # Wait Until Visible And Click ${HOME_BUTTON} 20s
这里额外加了可选的${timeout}参数,默认复用Robot全局的${TIMEOUT}变量(默认10秒),比固定逻辑更灵活。
方法二:用Python扩展SeleniumLibrary(进阶场景)
如果后续需要添加更复杂的逻辑(比如失败重试、自定义日志、异常处理),可以用Python写一个自定义库继承SeleniumLibrary:
from robot.libraries.BuiltIn import BuiltIn class CustomSeleniumHelper: def __init__(self): # 获取已加载的SeleniumLibrary实例 self.selenium = BuiltIn().get_library_instance("SeleniumLibrary") def wait_until_visible_and_click(self, locator, timeout=None): # 调用原生等待方法 self.selenium.wait_until_element_is_visible(locator, timeout=timeout) # 调用原生点击方法 self.selenium.click_button(locator)
使用步骤
- 把代码保存为
CustomSeleniumHelper.py - 在Robot测试文件中导入这个自定义库:
*** Settings *** Library CustomSeleniumHelper.py
- 直接调用自定义关键字:
Wait Until Visible And Click ${HOME_BUTTON}
两种方法里,第一种是最适合你的基础场景,不用额外写Python代码,直接在Robot文件里就能搞定,快速又省心。
内容的提问来源于stack exchange,提问作者cwezza
相关产品推荐
相关产品推荐

