Search code examples
python-2.7robotframeworkbuilt-in

Store Text into an Scalar within If / Else Statement - Robot Framework


I want to accomplish the following into Robot Framework

I want to store a Text from an Element xpath://*[@id="plsAttachGrid_0_1"]into a Scalar ${name3}, however, the Element is not always available on the web page, therefore, I need to run a IF/ELSE statement in order to avoid an Error when the Element is not available

My idea was the following:

${countt2}=    Get Element Count    xpath://*[@id="plsAttachGrid_0_1"]
Run Keyword If    ${countt2}>0    
${name3}=    Get Text    xpath://*[@id="plsAttachGrid_0_1"]
ELSE    LOG    NO_FILE

However, I have learnt It is not possible to store into a Scalar inside Run Keyword If, since it is expecting a Keyword.

Therefore, how can I accomplish it?


Solution

  • A keyword inside Run Keyword If can return a value that propagates up - e.g. can be assigned to a variable placed before the Run Keyword If; so in your case:

    ${name3}=    Run Keyword If    ${countt2}>0        Get Text    xpath://*[@id="plsAttachGrid_0_1"]
    

    So now ${name3} will have the return value of Get Text when ${countt2}>0.
    What will its value be if the condition is not met? It'll be None (the data type, not a string), as the variable is now declared, but not explicitly defined.

    You can set it to a different value in this case, to handle it easier later in the code:

    ${name3}=    Run Keyword If    ${countt2}>0        Get Text    xpath://*[@id="plsAttachGrid_0_1"]
                     ...           ELSE                Set Variable     not_set  # or ${0}, or any other value you need for ${countt2}<=0