Robotframework - 使用 Run 关键字 If /ELSE 时出错

时间:2021-04-17 16:29:35

标签: selenium robotframework

我正在努力使用 Selenium 在机器人框架中创建一个测试用例。 基本上我的目标是使用一些 xpath 查询在 FOR 循环中捕获一些 web 元素,检查页面上存在的实际 web 元素,以防下一次没有通过。 我创建了以下脚本:

*** Test Cases ***
FOR     ${href}     IN      @{hrefs}
        Log     ${href}
    ${pl}=       Run Keyword And Continue On Failure    Get Element Count        xpath://a[contains(@href,'test')]
        ${photo_link}=    Run Keyword If    ${pl}> 0 Get WebElement    xpath://a[contains(@href,'test')]
            ${test_a}=    Set Variable    ${photo_link.get_attribute('innerHTML')}
    ELSE
        ${test_a}=  do something else
END
    Close All Browsers

但我总是出错:

'Else' is a reserved keyword. It must be in uppercase (ELSE) when used as a marker with 'Run Keyword If'.

检查文档我找不到任何解决方案。 我使用了错误的语法吗? 是否有其他方法可以避免和跳过不匹配的“获取 WebElements”? 谢谢

1 个答案:

答案 0 :(得分:3)

有几个语法错误,框架解析器为其中一个抛出异常 - 当这个错误被修复时,你会看到另一个。从“隐藏的错误”开始,在这里:

Run Keyword If    ${pl}> 0 Get WebElement

,条件 ${pl}>0 和为 true 时的操作(获取 Webelement)之间没有分隔符(2 个或更多空格)。应该是

Run Keyword If    ${pl}> 0    Get WebElement

您看到的错误是由于使用了保留关键字ELSE;一般来说,它用于在条件为假时规定动作,并且是对 Run Keyword If 调用的一部分,例如应该写成:

Run Keyword If     condition    Action If True    ELSE    Action If False

或者像这样 - 有 3 个点,用于继续 - 当写在多行上时:

Run Keyword If     condition    Action If True    
...    ELSE    Action If False

你缺乏“延续”(我当场编造的一个术语,不要在上面引用我:),用户指南使用了其他东西) - 这是一个独立的 &独立线,因此错误。


为了修复它,您最好使用框架版本 4 中引入的新 IF/ELSE 块;它看起来像:

IF    ${pl}> 0
    ${photo_link}=    Get WebElement    xpath://a[contains(@href,'test')]
    ${test_a}=    Set Variable     ${photo_link.get_attribute('innerHTML')}
ELSE
    ${test_a}=    do something else
END

它看起来与您的代码几乎相同,但不使用 Run Keyword If。在 RF v3.x 中,通过使用关键字,您必须使用 Run Keywords 在真正的 blcok 中使用多个关键字,并且 - 您不能在 Run Keywords 内进行变量分配。您想要实现的目标可以在那里完成,流程略有不同,看起来有点尴尬,但新的 IF/ELSE 语法是您最安全的选择。

相关问题