Search code examples
pythonseleniumrobotframework

robot framework selenium How to retrieve a key from a diccionary


Recently I am attempting doing automation test in python with selenium-robot framework in two different browsers, but I am having an error when i try log the Alias of a Browser. The error says: "Dictionary '@{alias}' has no key '1'".

The code is this on:

*** Settings ***
Library  SeleniumLibrary

*** Variables ***
${url}  http://google.com
${browser}  chrome

*** Test Cases ***
TC to demostrate Browser Operation Keywords in Robot Framework
    [Documentation]  TC to demostrate Browser Operation Keywords in Robot Framework

    Open Browser  http://google.com  Chrome  alias=ChromeRCV

    Maximize Browser Window

    Open Browser  about:blank  ff  alias=RCVFF

    &{alias}  Get Browser Aliases

    Log  @{alias}[1]

    @{browser_ID}  Get Browser Ids

    Log  @{browser_ID}[1]

    Switch Browser  1

    Input Text  //*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input  RCVAcademy

    Sleep  4s

    Switch Browser  @{alias}[1]

    Go To  http://salesforce.com

    Close All Browsers

Solution

  • This is due to how Robot interprets the variables. Since you have written @{alias}[1] Robot assumes that the value on index 1 of list alias is also a list. To avoid this issue in future, think first what you want to get out from the variable before assigning the $, @ or &. You can see better explanation in the Robot Framework User Guide.

    Consider the below example

    &{DICT}=    {"key1": "value1", "key2": "value2"}
    
    # Get a list of keys
    @{KEYS}=    @{DICT.keys}
    # ==> @{KEYS}= ["key1", "key2]
    
    # Get a value from dictionary
    ${VALUE}=    ${DICT}[key1]
    # ==> ${VALUE}= value1
    
    # Get a value from list
    ${VALUE}=    ${LIST}[0]
    # ==> ${VALUE}= key1
    

    As you can see, only when returning a list value, are we using the @ sign. This is because whenever using the @ sign, Robot will interpret the given value as a list of multiple values and attempt to pass each value separately - This is also why normally lists are passed with $ as arguments to make Robot pass them as single variable instead of multiple separate values.

    Additionally you are attempting to return a value from a dictionary with a list-like index. This will not work that way - You'll either have to access the value based on the key or then as a list of keys or values.

    Since you only need the key to access the browser with the alias, you might as well simply use the following

    Log    ${aliases.keys()}[1]
    
    # or to log everything in the dictionary
    
    Log    ${aliases}