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

Robotframework - error when using Run Keyword If /ELSE

我正在努力使用 Selenium 在 robotframework 中创建一个测试用例。 基本上我的目标是使用一些 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”? 谢谢

有几个语法错误,框架解析器会为其中一个抛出异常 - 修复此错误后您会看到另一个。从“隐藏的错误”开始,在这篇文章中:

Run Keyword If    ${pl}> 0 Get WebElement

,条件${pl}>0和为真时的动作(Get Webelements)之间没有分隔符(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 语法是你最安全的选择。