【问题标题】:Robotframework - error when using Run Keyword If /ELSERobotframework - 使用 Run Keyword If /ELSE 时出错
【发布时间】:2021-04-19 00:55:08
【问题描述】:

我正在努力使用 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'.

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

【问题讨论】:

    标签: selenium robotframework


    【解决方案1】:

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

    Run Keyword If    ${pl}> 0 Get WebElement
    

    ,条件${pl}>0 和为真时的操作(获取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 语法是您最安全的选择。

    【讨论】:

    • 使用新语法的示例需要在ELSE 之后添加END。
    • 谢谢@BenceKaulics(你应该直接编辑它:)
    • 是的,我应该有,但我不喜欢编辑新鲜的答案,它们往往会发生很大变化。 :)
    猜你喜欢
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    相关资源
    最近更新 更多