Add Style Tag

Adds a <style type="text/css"> tag with the content.

Arguments

Argument Type Default value Description
contentstrnull

content Raw CSS content to be injected into frame.

Examples

Add Style Tag    \#username_field:focus {background-color: aqua;}

Comment >>

Check Checkbox

Checks the checkbox or selects radio button found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
forceboolFalse

selector Selector of the checkbox. See the Finding elements section for details about the selectors.

force Set to True to skip Playwright's Actionability checks.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Does nothing if the element is already checked/selected.

Comment >>

Clear Permissions

Clears all permissions from the current context.

Comment >>

Clear Text

Clears the text field found by selector.

Arguments

Argument Type Default value Description
selectorstrnull

selector Selector of the text field. See the Finding elements section for details about the selectors.

Keyword uses strict mode, see Finding elements for more details about strict mode.

See Type Text for emulating typing text character by character. See Fill Text for direct filling of the full text at once.

Comment >>

Click

Simulates mouse click on the element found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
buttonMouseButtonleft
clickCountint1
delaytimedelta, NoneNone
position_xfloat, NoneNone
position_yfloat, NoneNone
forceboolFalse
noWaitAfterboolFalse
modifiersKeyboardModifiernull

This keyword clicks an element matching selector by performing the following steps:

  • Find an element matches selector. If there is none, wait until a matching element is attached to the DOM.
  • Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  • Scroll the element into view if needed.
  • Use Mouse Button to click in the center of the element, or the specified position.
  • Wait for initiated navigation to either succeed or fail, unless noWaitAfter option is set.

selector Selector element to click. See the Finding elements section for details about the selectors.

button Defaults to left if invalid.

clickCount Defaults to 1.

delay Time to wait between mouse-down and mouse-up. Defaults to 0.

position_x & position_y A point to click relative to the top-left corner of element bounding-box. Only positive values within the bounding-box are allowed. If not specified, clicks to some visible point of the element.

force Set to True to skip Playwright's Actionability checks.

noWaitAfter Actions that initiate navigation, are waiting for these navigation to happen and for pages to start loading. You can opt out of waiting via setting this flag. You would only need this option in the exceptional cases such as navigating to inaccessible pages. Defaults to False.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Examples

Click    id=button_location
Click    \#clickWithOptions    delay=100ms    clickCount=2

*modifiers Modifier keys to press. Ensures that only these modifiers are pressed during the click, and then restores current modifiers back. If not specified, currently pressed modifiers are used. Modifiers can be specified in any order, and multiple modifiers can be specified. Valid modifier keys are Control, Alt, Shift and Meta. Due to the fact that the argument *modifiers is a positional only argument, all preceding keyword arguments have to be specified as positional arguments before *modifiers.

Example:

Click    id=clickWithModifiers    left    1    None    None    None    False    False    Alt    Meta    Shift
Click    id=clickWithModifier    right    2    None    None    None    False    False    Shift

Comment >>

Close Browser

Closes the current browser.

Arguments

Argument Type Default value Description
browserstrCURRENT

Active browser is set to the browser that was active before this one. Closes all context and pages belonging to this browser. See Browser, Context and Page for more information about Browser and related concepts.

browser < CURRENT | ALL | str > If value is not CURRENT it should be a string referencing the id of the browser to be closed. If ALL is provided Close All Browsers is executed.

Examples

Close Browser    ALL        # Closes all browsers
Close Browser    CURRENT    # Close current browser
Close Browser               # Close current browser
Close Browser    ${id}      # Close browser matching id

Comment >>

Close Context

Closes a Context.

Arguments

Argument Type Default value Description
contextstrCURRENT
browserstrCURRENT

Active context is set to the context that was active before this one. Closes pages belonging to this context. See Browser, Context and Page for more information about Context and related concepts.

context < CURRENT | ALL | str > Close context with specified id. If ALL is passed, all contexts of the specified browser are closed. Defaults to CURRENT.

browser < CURRENT | ALL | str > Close context in specified browser. If value is not "CURRENT" it should be a string referencing the id of the browser where to close context.

Examples

Close Context                          #  Closes current context and current browser
Close Context    CURRENT    CURRENT    #  Closes current context and current browser
Close Context    ALL        CURRENT    #  Closes all context from current browser and current browser
Close Context    ALL        ALL        #  Closes all context from current browser and all browser

Comment >>

Close Page

Closes the page in context in browser.

Arguments

Argument Type Default value Description
pagestrCURRENT
contextstrCURRENT
browserstrCURRENT

Defaults to current for all three. Active page is set to the page that was active before this one. See Browser, Context and Page for more information about Page and related concepts.

page < CURRENT | ALL | str > Id of the page to close. If value is not "CURRENT" it should be a string referencing the id of the context where to close page. If ALL is passed, all pages of the given context are closed. Defaults to CURRENT.

context < CURRENT | ALL | str > Id of the context that belongs to the page to be closed. If ALL is passed, the requested pages of all contexts are closed. Defaults to CURRENT.

browser < CURRENT | ALL | str > Id of the browser that belongs to the page to be closed. If ALL is passed, the requested pages depending of the context of all browsers are closed. Defaults to CURRENT.

Returns a list of dictionaries containing id, errors and console messages from the page.

Example

Close Page                                       # Closes current page, within the current context and browser
Close Page    CURRENT     CURRENT     CURRENT    # Closes current page, within the current context and browser
Close Page    ALL         ALL         ALL        # Closes all pages, within all contexts and browsers

Comment >>

Connect To Browser

Connect to a playwright Browser.

Arguments

Argument Type Default value Description
wsEndpointstrnull
browserSupportedBrowserschromium

See Browser, Context and Page for more information about Browser and related concepts.

Returns a stable identifier for the connected browser.

wsEndpoint Address to connect to.

browser Opens the specified browser. Defaults to chromium.

Comment >>

Crawl Site

Web crawler is a tool to go through all the pages on a specific URL domain. This happens by finding all links going to the same site and opening those.

Arguments

Argument Type Default value Description
urlstr, NoneNone
page_crawl_keywordtake_screenshot
max_number_of_page_to_crawlint1000
max_depth_to_crawlint50

returns list of crawled urls.

url is the page to start crawling from.

page_crawl_keyword is the keyword that will be executed on every page. By default it will take a screenshot on every page.

max_number_of_page_to_crawl is the upper limit of pages to crawl. Crawling will stop if the number of crawled pages goes over this.

max_depth_to_crawl is the upper limit of consecutive links followed from the start page. Crawling will stop if there are no more links under this depth.

Comment >>

Delete All Cookies

Deletes all cookies from the currently active browser context.

Comment >>

Deselect Options

Deselects all options from select element found by selector.

Arguments

Argument Type Default value Description
selectorstrnull

selector Selector of the select tag. See the Finding elements section for details about the selectors.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Comment >>

Download

Download given url content.

Arguments

Argument Type Default value Description
urlstrnull

Keyword returns dictionary which contains downloaded file path and suggested filename as keys (saveAs and suggestedFilename). If the file URL cannot be found (the download is triggered by event handlers) use Wait For Downloadkeyword.

To enable downloads context's acceptDownloads needs to be true.

To configure download directory use New Browser's downloadsPath settings

With default filepath downloaded files are deleted when Context the download happened in is closed.

This keyword requires that there is currently an open page. The keyword uses the current pages local state (cookies, sessionstorage, localstorage) for the download to avoid authentication problems.

Examples

${file_object}=    Download    ${url}
${actual_size}=    Get File Size    ${file_object.saveAs}

Example 2:

${elem}=          Get Element   text="Download File"
${href}=          Get Property  ${elem}  href

| ${file_object}= Download ${href}

${file_path}=     Set Variable  ${file_object.saveAs}

Comment >>

Drag And Drop

Executes a Drag&Drop operation from the element selected by selector_from to the element selected by selector_to.

Arguments

Argument Type Default value Description
selector_fromstrnull
selector_tostrnull
stepsint1

See the Finding elements section for details about the selectors.

First it moves the mouse to the start-point, then presses the left mouse button, then moves to the end-point in specified number of steps, then releases the mouse button.

Start- and end-point are defined by the center of the elements boundingbox.

selector_from identifies the element, which center is the start-point.

selector_to identifies the element, which center is the end-point.

steps defines how many intermediate mouse move events are sent.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Example

Drag And Drop    "Circle"    "Goal"

Comment >>

Drag And Drop By Coordinates

Executes a Drag&Drop operation from a coordinate to another coordinate.

Arguments

Argument Type Default value Description
from_xfloatnull
from_yfloatnull
to_xfloatnull
to_yfloatnull
stepsint1

First it moves the mouse to the start-point, then presses the left mouse button, then moves to the end-point in specified number of steps, then releases the mouse button.

Start- and end-point are defined by x and y coordinates relative to the top left corner of the pages viewport.

from_x & from_y identify the start-point.

to_x & to_y identify the end-point.

steps defines how many intermediate mouse move events are sent.

Examples

Drag And Drop By Coordinates
...    from_x=30    from_y=30
...    to_x=10    to_y=10    steps=200

Comment >>

Drag And Drop Relative To

Executes a Drag&Drop operation from the element selected by selector_from to coordinates relative to the center of that element.

Arguments

Argument Type Default value Description
selector_fromstrnull
xfloat0.0
yfloat0.0
stepsint1

This keyword can be handy to simulate swipe actions.

See the Finding elements section for details about the selectors.

First it moves the mouse to the start-point (center of boundingbox), then presses the left mouse button, then moves to the relative position with the given intermediate steps, then releases the mouse button.

selector_from identifies the element, which center is the start-point.

x & y identifies the end-point which is relative to the start-point.

steps defines how many intermediate mouse move events are sent.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Example

Drag And Drop Relative to    "Circle"    -20    0     # Slides the element 20 pixel to the left

Comment >>

Eat All Cookies

Eat all cookies for all easter.

Comment >>

Evaluate JavaScript

Executes given javascript on the selected element(s) or on page.

Arguments

Argument Type Default value Description
selectorstr, NoneNone
functionstrnull
argAny, NoneNone
all_elementsboolFalse

selector Selector to resolve and pass to the JavaScript function. This will be the first argument the function receives if not ${None}. selector is optional and can be omitted. If given a selector, a function is necessary, with an argument to capture the elementHandle. For example (element) => document.activeElement === element See the Finding elements section for details about the selectors.

*function A valid javascript function or a javascript function body. These arguments can be used to write readable multiline JavaScript.

arg an additional argument that can be handed over to the JavaScript function. This argument must be JSON serializable. ElementHandles are not supported.

all_elements defines if only the single elementHandle found by selector is handed over to the function or if set to True all found elements are handed over as array.

Example with all_elements=True:

 ${texts}=    Evaluate JavaScript    button
 ...    (elements, arg) => {
 ...        let text = []
 ...            for (e of elements) {
 ...                console.log(e.innerText)
 ...                text.push(e.innerText)
 ...            }
 ...        text.push(arg)
 ...        return text
 ...    }
 ...    all_elements=True
 ...    arg=Just another Text

Keyword uses strict mode if all_elements is False. See Finding elements for more details about strict mode.

Usage examples.

Comment >>

Execute JavaScript

DEPRECATED!! Use keyword Evaluate JavaScript instead. This keyword will be removed end of 2022.

Arguments

Argument Type Default value Description
functionstrnull
selectorstr

Executes given javascript on the page.

function A valid javascript function or a javascript function body. For example () => true and true will behave similarly.

selector Selector to resolve and pass to the JavaScript function. This will be the first argument the function receives. If given a selector a function is necessary, with an argument to capture the elementhandle. For example (element) => document.activeElement === element See the Finding elements section for details about the selectors.

Same functionality can be replaced with newer Evaluate JavaScript Keyword:

-    Execute JavaScript    (elem) => elem.innerText = "abc"    h1
+    Evaluate JavaScript    h1    (elem) => elem.innerText = "abc"

Example for replacement without Selector:

-    Execute JavaScript    () => document.location.hostname
+    Evaluate JavaScript    ${None}    () => document.location.hostname

Keyword uses strict mode if selector is defined. See Finding elements for more details about strict mode.

Usage examples.

Comment >>

Fill Secret

Fills the given secret from variable_name into the text field found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
secretstrnull
forceboolFalse

This keyword does not log secret in Robot Framework logs, when keywords resolves the secret variable internally. When secret variable is prefixed with $, without the curly braces, library will resolve the corresponding Robot Framework variable. If secret variable is prefixed with %, library will resolve corresponding environment variable. Example $Password` will resolve to ${Password} Robot Framework variable. Also %ENV_PWD will resolve to %{ENV_PWD} environment variable. Using normal Robot Framework variables or plain text will also work, but then library can not prevent Robot Framework leaking the secrets in the output files. Also library will log a warning if library can not resolve the secret internally.

If enable_playwright_debug is enabled in the library import, secret will be always visible as plain text in the playwright debug logs, regardless of the Robot Framework log level.

selector Selector of the text field. See the Finding elements section for details about the selectors.

force Set to True to skip Playwright's Actionability checks.

Keyword uses strict mode, see Finding elements for more details about strict mode.

See Fill Text for other details.

Examples

Fill Secret    input#username_field    $username    # Keyword resolves variable value from Robot Framework variables
Fill Secret    input#username_field    %username    # Keyword resolves variable value from environment variables

Comment >>

Fill Text

Clears and fills the given txt into the text field found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
txtstrnull
forceboolFalse

This method waits for an element matching the selector to appear, waits for actionability checks, focuses the element, fills it and triggers an input event after filling.

If the element matching selector is not an <input>, <textarea> or [contenteditable] element, this method throws an error. Note that you can pass an empty string as txt to clear the input field.

selector Selector of the text field. See the Finding elements section for details about the selectors.

txt Text for the text field.

force Set to True to skip Playwright's Actionability checks.

Keyword uses strict mode, see Finding elements for more details about strict mode.

See Type Text for emulating typing text character by character.

Examples

Fill Text    css=input#username_field    username

Comment >>

Focus

Moves focus on to the element found by selector.

Arguments

Argument Type Default value Description
selectorstrnull

selector Selector of the element. See the Finding elements section for details about the selectors.

Keyword uses strict mode, see Finding elements for more details about strict mode.

If there's no element matching selector, the method waits until a matching element appears in the DOM. Timeouts after 10 seconds.

Comment >>

Get Attribute

Returns the HTML attribute of the element found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
attributestrnull
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

selector Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.

attribute Requested attribute name.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the state

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that the attribute value matches the expected value. See Assertions for further details for the assertion arguments. By default assertion is not done.

When a attribute is selected that is not present and no assertion operator is set, the keyword fails. If an assertion operator is set and the attribute is not present, the returned value is None. This can be used to assert check the presents or the absents of an attribute.

Example Element:

<button class="login button active" id="enabled_button" something>Login</button>

Example Code:

Get Attribute   id=enabled_button    disabled                   # FAIL => "Attribute 'disabled' not found!"
Get Attribute   id=enabled_button    disabled     ==    ${None}     # PASS => returns: None
Get Attribute   id=enabled_button    something    evaluate    value is not None    # PASS =>  returns: True
Get Attribute   id=enabled_button    disabled     evaluate    value is None        # PASS =>  returns: True

Comment >>

Get Attribute Names

Returns all HTML attribute names of an element as a list.

Arguments

Argument Type Default value Description
selectorstrnull
assertion_operatorAssertionOperator, NoneNone
assertion_expectednull
messagestr, NoneNone

selector Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the state

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that attribute names do match to the expected value. See Assertions for further details for the assertion arguments. By default assertion is not done.

Available assertions:

  • == and != can work with multiple values
  • contains / *= only accepts one single expected value

Other operators are not allowed.

message overrides the default error message.

Examples

Get Attribute Names    [name="readonly_input"]    ==    type    name    value    readonly    # Has exactly these attribute names.
Get Attribute Names    [name="readonly_input"]    contains    disabled    # Contains at least this attribute name.

Comment >>

Get BoundingBox

Gets elements size and location as an object {x: float, y: float, width: float, height: float}.

Arguments

Argument Type Default value Description
selectorstrnull
keyBoundingBoxFieldsALL
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

selector Selector from which shall be retrieved. See the Finding elements section for details about the selectors.

key Optionally filters the returned values. If keys is set to ALL (default) it will return the BoundingBox as Dictionary, otherwise it will just return the single value selected by the key. Note: If a single value is retrieved, an assertion does not need a validate combined with a cast of value.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the counting

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that the value matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

Example use:

${bounding_box}=    Get BoundingBox    id=element                 # unfiltered
Log                 ${bounding_box}                                 # {'x': 559.09375, 'y': 75.5, 'width': 188.796875, 'height': 18}
${x}=               Get BoundingBox    id=element    x            # filtered
Log                 X: ${x}                                         # X: 559.09375
# Assertions:
Get BoundingBox     id=element         width         >    180
Get BoundingBox     id=element         ALL           validate    value['x'] > value['y']*2

Comment >>

Get Browser Catalog

Returns all browsers, open contexts in them and open pages in these contexts.

Arguments

Argument Type Default value Description
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

See Browser, Context and Page for more information about these concepts.

message overrides the default error message.

The data is parsed into a python list containing data representing the open Objects.

On the root level the data contains a list of open browsers.

Data can be manipulated also with assertion_operator for example to find a specific id based on index or page title with then operator.

Return value can also be asserted against expected value.

Sample:

[
  {
    "type": "chromium",
    "id": "browser=96207191-8147-44e7-b9ac-5e04f2709c1d",
    "contexts": [
      {
        "type": "context",
        "id": "context=525d8e5b-3c4e-4baa-bfd4-dfdbc6e86089",
        "activePage": "page=f90c97b8-eaaf-47f2-98b2-ccefd3450f12",
        "pages": [
          {
            "type": "page",
            "title": "Robocorp",
            "url": "https://robocorp.com/",
            "id": "page=7ac15782-22d2-48b4-8591-ff17663fa737",
            "timestamp": 1598607713.858
          },
          {
            "type": "page",
            "title": "Home - Reaktor",
            "url": "https://www.reaktor.com/",
            "id": "page=f90c97b8-eaaf-47f2-98b2-ccefd3450f12",
            "timestamp": 1598607714.702
          }
        ]
      }
    ],
    "activeContext": "context=525d8e5b-3c4e-4baa-bfd4-dfdbc6e86089",
    "activeBrowser": false
  },
  {
    "type": "firefox",
    "id": "browser=ad99abac-17a9-472b-ac7f-d6352630834e",
    "contexts": [
      {
        "type": "context",
        "id": "context=bc64f1ba-5e76-46dd-9735-4bd344afb9c0",
        "activePage": "page=8baf2991-5eaf-444d-a318-8045f914e96a",
        "pages": [
          {
            "type": "page",
            "title": "Software-Qualitätssicherung und Softwaretest",
            "url": "https://www.imbus.de/",
            "id": "page=8baf2991-5eaf-444d-a318-8045f914e96a",
            "timestamp": 1598607716.828
          }
        ]
      }
    ],
    "activeContext": "context=bc64f1ba-5e76-46dd-9735-4bd344afb9c0",
    "activeBrowser": true
  }
]

Comment >>

Get Browser Ids

Returns a list of ids from open browsers. See Browser, Context and Page for more information about Browser and related concepts.

Arguments

Argument Type Default value Description
browserSelectionTypeALL

browser Defaults to ALL

  • ALL / ANY Returns all ids as a list.
  • ACTIVE / CURRENT Returns the id of the currently active browser as list.

The ACTIVE browser is a synonym for the CURRENT Browser.

Comment >>

Get Checkbox State

Returns the state of the checkbox found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
assertion_operatorAssertionOperator, NoneNone
expected_statebool, strUnchecked
messagestr, NoneNone

selector Selector which shall be examined. See the Finding elements section for details about the selectors.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the state

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that the state matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

  • == and != and equivalent are allowed on boolean values
  • other operators are not accepted.

expected_state boolean value of expected state. Strings are interpreted as booleans. All strings are ${True} except of the following FALSE, NO, OFF, 0, UNCHECKED, NONE, ${EMPTY}`. (case-insensitive). Defaults to unchecked

  • checked => True
  • unchecked => False

Examples

Get Checkbox State    [name=can_send_email]    ==    checked

Comment >>

Get Classes

Returns all classes of an element as a list.

Arguments

Argument Type Default value Description
selectorstrnull
assertion_operatorAssertionOperator, NoneNone
assertion_expectednull
messagestr, NoneNone

selector Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the state

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that the value matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

Available assertions:

  • == and != can work with multiple values
  • contains / *= only accepts one single expected value

Other operators are not allowed.

Examples

Get Classes    id=draggable    ==    react-draggable    box    # Element contains exactly this class name.
Get Classes    id=draggable    validate    "react-draggable-dragged" not in value    # Element does not contain react-draggable-dragged class.

Comment >>

Get Client Size

Gets elements or pages client size (clientHeight, clientWidth) as object {width: float, height: float}.

Arguments

Argument Type Default value Description
selectorstr, NoneNone
keySizeFieldsALL
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

selector Optional selector from which shall be retrieved. If no selector is given the client size of the page itself is used (document.scrollingElement). See the Finding elements section for details about the selectors.

key Optionally filters the returned values. If keys is set to ALL (default) it will return the scroll size as dictionary, otherwise it will just return the single value selected by the key.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the counting

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that the value matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

See Get BoundingBox or Get Scroll Size for examples.

Comment >>

Get Context Ids

Returns a list of context ids based on the browser selection. See Browser, Context and Page for more information about Context and related concepts.

Arguments

Argument Type Default value Description
contextSelectionTypeALL
browserSelectionTypeALL

ALL and ANY are synonyms. ACTIVE and CURRENT are also synonyms.

context Defaults to ALL

  • ALL Returns all context ids as a list.
  • ACTIVE Returns the id of the active context as a list.

browser Defaults to ALL

  • ALL context ids from all open browsers shall be fetched.
  • ACTIVE only context ids from the active browser shall be fetched.

The ACTIVE context of the ACTIVE Browser is the Current Context.

Comment >>

Get Cookies

Returns cookies from the current active browser context.

Arguments

Argument Type Default value Description
return_typeCookieTypedictionary

If return_type is dictionary or dict then keyword returns list of Robot Framework dot dictionaries The dictionary contains all possible key value pairs of the cookie. See Get Cookie keyword documentation about the dictionary keys and values.

If return_type is string or str, then keyword returns the cookie as a string in format: name1=value1; name2=value2; name3=value3. The return value contains only name and value keys of the cookie.

Comment >>

Get Device

Get a single device descriptor with name exactly matching name.

Arguments

Argument Type Default value Description
namestrnull

name Given name of the requested device. See Playwright's deviceDescriptorsSource.json for a formatted list.

Allows a concise syntax to set website testing values to exact matches of specific mobile devices.

Use by passing to a context. After creating a context with devicedescriptor, before using ensure your active page is on that context. Usage:

${device}=          Get Device       iPhone X
New Context         &{device}
New Page
Get Viewport Size   # returns { "width": 375, "height": 812 }

Comment >>

Get Devices

Returns a dict of all playwright device descriptors.

See Playwright's deviceDescriptorsSource.json for a formatted list.

Comment >>

Get Element

Returns a reference to a Playwright Locator.

Arguments

Argument Type Default value Description
selectorstrnull

The reference can be used in subsequent selectors.

selector Selector from which shall be retrieved . See the Finding elements section for details about the selectors.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Examples

${element} =    Get Element    \#username_field
${option_value} =    Get Property    ${element} >> optionOne    value    # Locator is resolved from the page.
${option_value} =    Get Property    ${element} >> optionTwo    value    # Locator is resolved again from the page.

Comment >>

Get Element Count

Returns the count of elements found with selector.

Arguments

Argument Type Default value Description
selectorstrnull
assertion_operatorAssertionOperator, NoneNone
expected_valueint, str0
messagestr, NoneNone

selector Selector which shall be counted. See the Finding elements section for details about the selectors.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the counting

message overrides the default error message for assertion.

Optionally asserts that the state matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

Examples

Get Element Count    label    >    1

Comment >>

Get Element State

DEPRECATED!! Use keyword Get Element States instead. This keyword will be removed end of 2022.

Arguments

Argument Type Default value Description
selectorstrnull
stateElementStatevisible
assertion_operatorAssertionOperator, NoneNone
assertion_expectedstr, NoneNone
messagestr, NoneNone

Get the given state from the element found by selector.

Refactoring example assertion:

-    Get Element State    h1    readonly    ==    False
+    Get Element States    h1    not contains    readonly

Refactoring example asserting multiple states:

-    Get Element State    id=password    visible    ==    True
-    Get Element State    id=password    readonly    ==    False
-    Get Element State    id=password    disabled    ==    False
+    Get Element States    h1    contains    visible    editable    enabled

Refactoring example for getting state:

-    ${visibility}    Get Element State    h1    visible
+    ${visibility}    Get Element States    h1    then    bool(value & visible)  # Returns ${True} if element is visible.

If the selector does satisfy the expected state it will return True otherwise False.

selector Selector of the corresponding object. See the Finding elements section for details about the selectors.

state Defaults to visible. Possible states are

Note that element must be attached to DOM to be able to fetch the state of readonly , selected and checked. The other states are false if the requested element is not attached.

Note that element without any content or with display:none has an empty bounding box and is not considered visible.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the counting

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that the state matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

Examples

Get Element State    h1    readonly    ==    False

Comment >>

Get Element States

Get the active states from the element found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
assertion_operatorAssertionOperator, NoneNone
assertion_expectedElementState, strnull
messagestr, NoneNone
return_namesTrue

This Keyword returns a list of states that are valid for the selected element. If Argument return_names=False is set the keyword does return an IntFlag] object instead of a list.

Optionally asserts that the state matches the specified assertion. See Assertions for further details for the assertion arguments. By default, assertion is not done.

This keyword internally works with Python IntFlag. Flags can be processed using bitwise operators like & (bitwise AND) and | (bitwise OR). When using the assertion operators then, evaluate or validate the value contain the states as ElementState.

Examples

Get Element States    h1    validate    value | visible
Get Element States    h1    then    value & (visible | hidden)  # returns either ['visible'] or ['hidden']
Get Element States    h1    then    bool(value & visible)  # Returns ${True} if element is visible

The most typical use case would be to verify if an element contains a specific state or multiple states.

Example:

Get Element States    id=checked_elem      *=    checked
Get Element States    id=checked_elem      not contains    checked
Get Element States    id=invisible_elem    contains    hidden    attached
Get Element States    id=disabled_elem     contains    visible    disabled    readonly

Elements do return the positive and negative values if applicable. As example, a checkbox does return either checked or unchecked while a text input element has none of those two states. Select elements have also either selected or unselected.

The state of animating will be set if an element is not considered stable within 300 ms.

If an element is not attached to the dom, so it can not be found within 250ms it is marked as detached as the only state.

stable state is not returned, because it would cause too high delay in that keyword.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Comment >>

Get Elements

Returns a reference to Playwright Locator for all matched elements by selector.

Arguments

Argument Type Default value Description
selectorstrnull

selector Selector from which shall be retrieved. See the Finding elements section for details about the selectors.

Examples

${elements} =    Get Elements
${elem} =    Get From List    ${elements}    0
${option_value} =    Get Property    ${elem} >> option    value

Comment >>

Get Page Ids

Returns a list of page ids based on the context and browser selection. See Browser, Context and Page for more information about Page and related concepts.

Arguments

Argument Type Default value Description
pageSelectionTypeALL
contextSelectionTypeALL
browserSelectionTypeALL

ALL and ANY are synonyms. ACTIVE and CURRENT are also synonyms.

page

  • ALL Returns all page ids as a list.
  • ACTIVE Returns the id of the active page as a list.

context

  • ALL page ids from all contexts shall be fetched.
  • ACTIVE only page ids from the active context shall be fetched.

browser

  • ALL page ids from all open browsers shall be fetched.
  • ACTIVE only page ids from the active browser shall be fetched.

Examples

Test Case
    New Page    http://www.imbus.de
    New Page    http://www.reaktor.com
    ${current_page}=   Get Page IDs    ACTIVE    ACTIVE    ACTIVE
    Log                Current page ID is: ${current_page}[0]
    ${all_pages}=      Get Page IDs    CURRENT   CURRENT   ALL
    Log Many           These are all Page IDs    @{all_pages}

The ACTIVE page of the ACTIVE context of the ACTIVE Browser is the Current Page.

Comment >>

Get Page Source

Gets pages HTML source as a string.

Arguments

Argument Type Default value Description
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the state

message overrides the default error message for assertion.

Optionally does a string assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

Comment >>

Get Property

Returns the property of the element found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
propertystrnull
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

selector Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.

property Requested property name.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the state

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that the property value matches the expected value. See Assertions for further details for the assertion arguments. By default assertion is not done.

If assertion_operator is set and property is not found, value is None and Keyword does not fail. See Get Attribute for examples.

Examples

Get Property    h1    innerText    ==    Login Page
${property} =    Get Property    h1    innerText

Comment >>

Get Scroll Position

Gets elements or pages current scroll position as object {top: float, left: float, bottom: float, right: float}.

Arguments

Argument Type Default value Description
selectorstr, NoneNone
keyAreaFieldsALL
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

It describes the rectangle which is visible of the scrollable content of that element. all values are measured from position {top: 0, left: 0}.

top uses js function scrollTop, left uses scrollLeft and bottom and right are calculated with the client size.

selector Optional selector from which shall be retrieved. If no selector is given the client size of the page itself is used (document.scrollingElement). See the Finding elements section for details about the selectors.

key Optionally filters the returned values. If keys is set to ALL (default) it will return the scroll position as dictionary, otherwise it will just return the single value selected by the key.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the counting

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that the value matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

See Get BoundingBox or Get Scroll Size for examples.

Comment >>

Get Scroll Size

Gets elements or pages scrollable size as object {width: float, height: float}.

Arguments

Argument Type Default value Description
selectorstr, NoneNone
keySizeFieldsALL
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

selector Optional selector from which shall be retrieved. If no selector is given the scroll size of the page itself is used. See the Finding elements section for details about the selectors.

key Optionally filters the returned values. If keys is set to ALL (default) it will return the scroll size as dictionary, otherwise it will just return the single value selected by the key.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the counting

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that the state matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

See Get BoundingBox for more similar examples.

Example use:

${height}=         Get Scroll Size    height                          # filtered page by height
Log                Width: ${height}                                   # Height: 58425
${scroll_size}=    Get Scroll Size    id=keyword-shortcuts-container  # unfiltered element
Log                ${scroll_size}                                     # {'width': 253, 'height': 3036}

Comment >>

Get Select Options

Returns attributes of options of a select element as a list of dictionaries.

Arguments

Argument Type Default value Description
selectorstrnull
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

Returned dictionaries have the following keys and their values "index", "value", "label" and "selected".

selector Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the state

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that these match the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

Examples

Get Select Options     //select[2]    validate  [v["label"] for v in value] == ["Email", "Mobile"]
Get Select Options   select#names     validate  any(v["label"] == "Mikko" for v in value)

Comment >>

Get Selected Options

Returns the specified attribute of selected options of the select element.

Arguments

Argument Type Default value Description
selectorstrnull
option_attributeSelectAttributelabel
assertion_operatorAssertionOperator, NoneNone
assertion_expectednull

selector Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.

option_attribute Which attribute shall be returned/verified. Defaults to label.

Keyword uses strict mode, see Finding elements for more details about strict mode.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the state

Optionally asserts that these match the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

  • == and != can work with multiple values
  • contains / *= only accepts one single expected value

Other operators are not allowed.

Examples

Select Options By      label                    //select[2]    Email      Mobile
${selected_list}         Get Selected Options   //select[2]                                         # getter
Get Selected Options   //select[2]              label          ==       Mobile             Mail   #assertion content
Select Options By      label                    select#names   2          4
Get Selected Options   select#names             index          ==       2                  4      #assertion index
Get Selected Options   select#names             label          *=         Mikko                     #assertion contain
Get Selected Options   select#names             label          validate   len(value) == 3           #assertion length

Comment >>

Get Style

Gets the computed style properties of the element selected by selector.

Arguments

Argument Type Default value Description
selectorstrnull
keystrALL
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

Optionally matches with any sequence assertion operator.

selector Selector from which the style shall be retrieved. See the Finding elements section for details about the selectors.

key Key of the requested CSS property. Retrieves "ALL" styles by default.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the counting

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that the style matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

Comment >>

Get Table Cell Element

Returns the Web Element that has the same column index and same row index as the selected elements.

Arguments

Argument Type Default value Description
tablestrnull
columnstrnull
rowstrnull

table selector must select the <table> element that contains both selected elements

column selector can select any <th> or <td> element or one of their descendants.

row selector can select any <tr> element or one of their descendant like <td> elements.

column and row can also consume index numbers instead of selectors. Indexes are starting from 0 and -1 is specific for the last element.

Selectors for column and row are directly appended to table selector like this: f"{table} >> {row}" .

GitHub Slack Real Name
mkorpela @mkorpela Mikko Korpela
aaltat @aaltat Tatu Aalto
xylix @Kerkko Pelttari Kerkko Pelttari
Snooz82 @René René Rohner

Examples

${table}=    Set Variable    id=Get Table Cell Element >> div.kw-docs table
${e}=    Get Table Cell Element    ${table}    "Real Name"    "aaltat"   # Returns element with text Tatu Aalto
Get Text    ${e}    ==    Tatu Aalto
${e}=    Get Table Cell Element    ${table}    "Slack"    "Mikko Korpela"   # Returns element with text @mkorpela
Get Text    ${e}    ==    @mkorpela
${e}=    Get Table Cell Element    ${table}    "mkorpela"    "Kerkko Pelttari"   # column does not need to be in row 0
Get Text    ${e}    ==    @mkorpela
${e}=    Get Table Cell Element    ${table}    2    -1   # Index is also directly possible
Get Text    ${e}    ==    René Rohner

Comment >>

Get Table Cell Index

Returns the index (0 based) of a table cell within its row.

Arguments

Argument Type Default value Description
selectorstrnull
assertion_operatorAssertionOperator, NoneNone
expected_valueint, str0
messagestr, NoneNone

selector can select any <th> or <td> element or one of their descendants. See the Finding elements section for details about the selectors.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the counting

message overrides the default error message for assertion.

Examples

${table}=    Set Variable    id=Get Table Cell Element >> div.kw-docs table   #Table of keyword Get Table Cell Element
${idx}=    Get Table Cell Index    ${table} >> "Real Name"
Should Be Equal    ${idx}    ${2}
Get Table Cell Index    ${table} >> "@aaltat"    ==    1

Optionally asserts that the index matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

Comment >>

Get Table Row Index

Returns the index (0 based) of a table row.

Arguments

Argument Type Default value Description
selectorstrnull
assertion_operatorAssertionOperator, NoneNone
expected_valueint, str0
messagestr, NoneNone

selector can select any <th> or <td> element or one of their descendants. See the Finding elements section for details about the selectors.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the counting

message overrides the default error message for assertion.

Examples

${table}=    Set Variable    id=Get Table Cell Element >> div.kw-docs table   #Table of keyword Get Table Cell Element
${idx}=    Get Table Row Index    ${table} >> "@René"
Should Be Equal    ${idx}    ${4}
Get Table Row Index    ${table} >> "@aaltat"    ==    2

Optionally asserts that the index matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

Comment >>

Get Text

Returns text attribute of the element found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

Keyword can also return input or textarea value property text.

See the Finding elements section for details about the selectors.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the state

message overrides the default error message for assertion.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Optionally asserts that the text matches the specified assertion. See Assertions for further details for the assertion arguments. By default, assertion is not done.

Examples

${text} =    Get Text    id=important                            # Returns element text without assertion.
${text} =    Get Text    id=important    ==    Important text    # Returns element text with assertion.
${text} =    Get Text    //input         ==    root              # Returns input element text with assertion.

Comment >>

Get Title

Returns the title of the current page.

Arguments

Argument Type Default value Description
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the state

message overrides the default error message for assertion.

Optionally asserts that title matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

message overrides the default error message.

Comment >>

Get Url

Returns the current URL.

Arguments

Argument Type Default value Description
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the state

message overrides the default error message for assertion.

Optionally asserts that it matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

message overrides the default error message.

Comment >>

Get Viewport Size

Returns the current viewport dimensions.

Arguments

Argument Type Default value Description
keySizeFieldsALL
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

key Optionally filters the returned values. If keys is set to ALL (default) it will return the viewport size as dictionary, otherwise it will just return the single value selected by the key. Note: If a single value is retrieved, an assertion does not need a validate combined with a cast of value.

assertion_operator See Assertions for further details. Defaults to None.

expected_value Expected value for the counting

message overrides the default error message for assertion.

Optionally asserts that the state matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.

Examples

Get Viewport Size    ALL    ==    {'width':1280, 'height':720}
Get Viewport Size    width    >=    1200

Comment >>

Go Back

Navigates to the previous page in history.

Comment >>

Go Forward

Navigates to the next page in history.

Comment >>

Go To

Navigates to the given url.

Arguments

Argument Type Default value Description
urlstrnull
timeouttimedelta, NoneNone

url <str> URL to be navigated to.

timeout <str> time to wait page to load. If not defined will use the library default timeout.

Comment >>

Grant Permissions

Grants permissions to the current context.

Arguments

Argument Type Default value Description
permissionsPermissionnull
originstr, NoneNone

`permissions` is a list of permissions to grant. Permissions can be one of the following: geolocation, notifications, camera, microphone,

Examples

New Context
Grant Permissions    geolocation

Comment >>

Handle Future Dialogs

Handle next dialog on page with action.

Arguments

Argument Type Default value Description
actionDialogActionnull
prompt_inputstr

Dialog can be any of alert, beforeunload, confirm or prompt. Handling dialogue must be called before the action, like example click, that triggers the dialogue.

If a handler is not set dialogs are dismissed by default.

action How to handle the alert.

prompt_input The value to enter into prompt. Only valid if action equals accept. Defaults to empty string.

Examples

Handle Future Dialogs    action=accept
Click                    \#alerts

Comment >>

Highlight Elements

Adds a highlight to elements matched by the selector. Provides a style adjustment.

Arguments

Argument Type Default value Description
selectorstrnull
durationtimedelta0:00:05
widthstr2px
stylestrdotted
colorstrblue

selector Selectors which shall be highlighted. See the Finding elements section for details about the selectors.

duration Sets for how long the selector shall be highlighted. Defaults to 5s => 5 seconds.

width Sets the width of the higlight border. Defaults to 2px.

style Sets the style of the border. Defaults to dotted.

color Sets the color of the border. Valid colors i.e. are: red, blue, yellow, pink, black

Keyword does not fail if selector resolves to multiple elements.

Examples

Highlight Elements    input#login_button    duration=200ms
Highlight Elements    input#login_button    duration=200ms    width=4px    style=solid    color=\#FF00FF

Comment >>

Hover

Moves the virtual mouse and scrolls to the element found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
position_xfloat, NoneNone
position_yfloat, NoneNone
forceboolFalse
modifiersKeyboardModifiernull

This method hovers over an element matching selector by performing the following steps:

  • Find an element match matching selector. If there is none, wait until a matching element is attached to the DOM.
  • Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  • Scroll the element into view if needed.
  • Use Mouse Move to hover over the center of the element, or the specified position.

selector Selector element to hover. See the Finding elements section for details about the selectors.

position_x & position_y A point to hover relative to the top-left corner of element bounding box. If not specified, hovers over some visible point of the element. Only positive values within the bounding-box are allowed.

force Set to True to skip Playwright's Actionability checks.

Keyword uses strict mode, see Finding elements for more details about strict mode.

*modifiers Modifier keys to press. Ensures that only these modifiers are pressed during the hover, and then restores current modifiers back. If not specified, currently pressed modifiers are used.

Examples

Hover    h1
Hover    h1    10   20    Alt

Comment >>

Http

Performs an HTTP request in the current browser context

Arguments

Argument Type Default value Description
urlstrnull
methodRequestMethodGET
bodystr, NoneNone
headersdict, NoneNone

Accepts the following arguments:

  • url The request url, e.g. /api/foo.
  • method The HTTP method for the request. Defaults to GET.
  • body The request body. GET requests cannot have a body. If the body can be parsed as JSON, the Content-Type header for the request will be automatically set to application/json. Defaults to None.
  • headers A dictionary of additional request headers. Defaults to None.

The response is a Python dictionary with following attributes:

  • status <int> The status code of the response.
  • statusText <str> Status text corresponding to status, e.g OK or INTERNAL SERVER ERROR.
  • body <dict> | <str> The response body. If the body can be parsed as a JSON obejct, it will be returned as Python dictionary, otherwise it is returned as a string.
  • headers <dict> A dictionary containing all response headers.
  • ok <bool> Whether the request was successfull, i.e. the status is range 200-299.

Here's an example of using Robot Framework dictionary variables and extended variable syntax to do assertions on the response object:

&{res}=             HTTP                       /api/endpoint
Should Be Equal     ${res.status}              200
Should Be Equal     ${res.body.some_field}     some value

Comment >>

Keyboard Input

Input text into page with virtual keyboard.

Arguments

Argument Type Default value Description
actionKeyboardInputActionnull
inputstrnull
delay0

action

  • insertText Dispatches only input event, does not emit the keydown, keyup or keypress events.
  • type Sends a keydown, keypress/input, and keyup event for each character in the text.

input The inputstring to be typed. No special keys possible.

Note: To press a special key, like Control or ArrowDown, use keyboard.press. Modifier keys DO NOT effect these methods. For testing modifier effects use single key presses with Keyboard Key press

Examples

Keyboard Input    insertText    0123456789

Comment >>

Keyboard Key

Press a keyboard key on the virtual keyboard or set a key up or down.

Arguments

Argument Type Default value Description
actionKeyActionnull
keystrnull

action Determine whether the key should be released, hold or pressed. down or up are useful for combinations i.e. with Shift.

key The key to be pressed. An example of valid keys are:

F1 - F12, Digit0 - Digit9, KeyA - KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp , etc.

Useful keys for down and up for example are:

Shift, Control, Alt, Meta, ShiftLeft

Example excecution:

Keyboard Key    press    S
Keyboard Key    down     Shift
Keyboard Key    press    ArrowLeft
Keyboard Key    press    Delete
Keyboard Key    up       Shift

Note: Capital letters don't need to be written by the help of Shift. You can type them in directly.

Comment >>

LocalStorage Clear

Remove all saved data from the local storage.

Examples

Local Storage Set Item      Foo    bar
LocalStorage Clear
${item} =    Local Storage Get Item    Foo
Should Be Equal    ${item}    ${None}

Comment >>

LocalStorage Get Item

Get saved data from the local storage.

Arguments

Argument Type Default value Description
keystrnull
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone
messagestr, NoneNone

key Named key of the item in the storage.

See Assertions for further details for the assertion arguments. Defaults to None.

Examples

Local Storage Get Item    Key    ==    Value    My error
${value} =    Local Storage Get Item    Key

Comment >>

LocalStorage Remove Item

Remove saved data with key from the local storage.

Arguments

Argument Type Default value Description
keystrnull

key Name of the item which shall be deleted.

Examples

Local Storage Set Item      Foo    bar
LocalStorage Remove Item    Foo
${item} =    Local Storage Get Item    Foo
Should Be Equal    ${item}    ${None}

Comment >>

LocalStorage Set Item

Save data to the local storage.

Arguments

Argument Type Default value Description
keystrnull
valuestrnull

key The name of the key under which it should be saved.

value The value which shall be saved as a string.

Examples

Local Storage Set Item    Key    Value

Comment >>

Mouse Button

Clicks, presses or releases a mouse button.

Arguments

Argument Type Default value Description
actionMouseButtonActionnull
xfloat, NoneNone
yfloat, NoneNone
buttonMouseButtonleft
clickCountint1
delayint0

action Determines if it is a mouseclick, holding down a key or releasing it.

x and y Coordinates to move before.

button Defaults to left.

clickCount Determine how often shall be clicked. Defaults to 1.

delay Delay in ms between the mousedown and mouseup event. Can only be set if the action is click.

Moving the mouse between holding down and releasing it, is possible with Mouse Move.

Examples

Hover                     "Obstacle"           # Move mouse over the element
Mouse Button              down                 # Press mouse button down
Mouse Move Relative To    "Obstacle"    500    # Drag mouse
Mouse Button              up                   # Release mouse button

Comment >>

Mouse Move

Instead of selectors command mouse with coordinates. The Click commands will leave the virtual mouse on the specified coordinates.

Arguments

Argument Type Default value Description
xfloatnull
yfloatnull
stepsint1

x y are absolute coordinates starting at the top left of the page.

steps Number of intermediate steps for the mouse event.

Examples

Mouse Move    400    400

Comment >>

Mouse Move Relative To

Moves the mouse cursor relative to the selected element.

Arguments

Argument Type Default value Description
selectorstrnull
xfloat0.0
yfloat0.0
stepsint1

x y are relative coordinates to the center of the elements bounding box.

steps Number of intermediate steps for the mouse event. This is sometime needed for websites to recognize the movement.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Examples

Mouse Move Relative To    id=indicator    -100

Comment >>

New Browser

Create a new playwright Browser with specified options.

Arguments

Argument Type Default value Description
browserSupportedBrowserschromium
headlessboolTrue
executablePathstr, NoneNone
argsList[str], NoneNone
ignoreDefaultArgsList[str], NoneNone
proxyProxy, NoneNone
downloadsPathstr, NoneNone
handleSIGINTboolTrue
handleSIGTERMboolTrue
handleSIGHUPboolTrue
timeouttimedelta0:00:30
envDict, NoneNone
devtoolsboolFalse
slowMotimedelta0:00:00
channelstr, NoneNone

See Browser, Context and Page for more information about Browser and related concepts.

Returns a stable identifier for the created browser.

browser Opens the specified browser. Defaults to chromium.

headless Set to False if you want a GUI. Defaults to True.

executablePath Path to a browser executable to run instead of the bundled one. If executablePath is a relative path, then it is resolved relative to current working directory. Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk. Defaults to None.

args Additional arguments to pass to the browser instance. The list of Chromium flags can be found here. Defaults to None.

ignoreDefaultArgs If an array is given, then filters out the given default arguments. Defaults to None.

proxy Network proxy settings.

  • server <string> Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example http://myproxy.com:3128 or socks5://myproxy.com:3128. Short form myproxy.com:3128 is considered an HTTP proxy.
  • bypass <string> Optional coma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com".
  • username <string> Optional username to use if HTTP proxy requires authentication.
  • password <string> Optional password to use if HTTP proxy requires authentication.

downloadsPath If specified, accepted downloads are downloaded into this folder. Otherwise, temporary folder is created and is deleted when browser is closed.

handleSIGINT Close the browser process on Ctrl-C. Defaults to True.

handleSIGTERM Close the browser process on SIGTERM. Defaults to True.

handleSIGHUP Close the browser process on SIGHUP. Defaults to True.

timeout Maximum time in milliseconds to wait for the browser instance to start. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

env <Dict<str, str|int|bool>> Specify environment variables that will be visible to the browser. Defaults to None.

devtools Chromium-only Whether to auto-open a Developer Tools panel for each tab. If this option is true, the headless option will be set false.

slowMo Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. Defaults to no delay.

channel Allows to operate against the stock Google Chrome and Microsoft Edge browsers. For more details see: Playwright documentation.

Comment >>

New Context

Create a new BrowserContext with specified options.

Arguments

Argument Type Default value Description
acceptDownloadsboolTrue
ignoreHTTPSErrorsboolFalse
bypassCSPboolFalse
viewportViewportDimensions, NoneNone
userAgentstr, NoneNone
deviceScaleFactorfloat1.0
isMobileboolFalse
hasTouchboolFalse
javaScriptEnabledboolTrue
timezoneIdstr, NoneNone
geolocationGeoLocation, NoneNone
localestr, NoneNone
permissionsList[Permission], NoneNone
extraHTTPHeadersDict[str, str], NoneNone
offlineboolFalse
httpCredentialsHttpCredentials, NoneNone
colorSchemeColorScheme, NoneNone
proxyProxy, NoneNone
videosPathstr, NoneNone
videoSizeViewportDimensions, NoneNone
defaultBrowserTypeSupportedBrowsers, NoneNone
hideRfBrowserboolFalse
recordVideoRecordVideo, NoneNone
recordHarRecordHar, NoneNone
tracingstr, NoneNone
screenDict[str, int], NoneNone
storageStatestr, NoneNone
reducedMotionReduceMotionno_preference
forcedColorsForcedColorsnone

See Browser, Context and Page for more information about BrowserContext.

Returns a stable identifier for the created context that can be used in Switch Context.

acceptDownloads Whether to automatically downloads all the attachments. Defaults to True where all the downloads are accepted.

ignoreHTTPSErrors Whether to ignore HTTPS errors during navigation. Defaults to False.

bypassCSP Toggles bypassing page's Content-Security-Policy. Defaults to False.

viewport Sets a consistent viewport for each page. Defaults to an {'width': 1280, 'height': 720} viewport. Value of viewport can be a dict or a string representation of a dictionary.

userAgent Specific user agent to use in this context.

deviceScaleFactor Specify device scale factor (can be thought of as dpr). Defaults to 1.

isMobile Whether the meta viewport tag is taken into account and touch events are enabled. Defaults to False. Not supported in Firefox.

hasTouch Specifies if viewport supports touch events. Defaults to False.

javaScriptEnabled Whether or not to enable JavaScript in the context. Defaults to True.

timezoneId Changes the timezone of the context. See ICU’s metaZones.txt for a list of supported timezone IDs.

geolocation Sets the geolocation. No location is set by default.

  • latitude <number> Latitude between -90 and 90.
  • longitude <number> Longitude between -180 and 180.
  • accuracy Optional <number> Non-negative accuracy value. Defaults to 0.

Example usage: {'latitude': 59.95, 'longitude': 30.31667}

locale Specify user locale, for example en-GB, de-DE, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting rules.

permissions A list of permissions to grant to all pages in this context. See grantPermissions for more details.

extraHTTPHeaders A dictionary containing additional HTTP headers to be sent with every request. All header values must be strings.

offline Whether to emulate network being offline. Defaults to False.

httpCredentials Credentials for HTTP authentication.

  • example: {'username': '$username', 'password': '$pwd'}
  • username
  • password

Direct usage of username and password is not recommended, but is possible. If username and password is directly used, it can leak secret information to Robot Framework output files. Instead the username and password values can be prefixed with $ or %. Then keyword will internally resolve the values and secrets are not leaked to Robot Framework output files. The $ prefix will resolve Robot Framework variable and % will resolve environment variable. If enable_playwright_debug is enabled, all secrets are written as plain text in Playwright debugs logs.

colorScheme Emulates 'prefers-colors-scheme' media feature, supported values are 'light', 'dark', 'no-preference'. See emulateMedia(options) for more details. Defaults to light.

proxy Network proxy settings to use with this context. Note that browser needs to be launched with the global proxy for this option to work. If all contexts override the proxy, global proxy will be never used and can be any string

videosPath is deprecated by playwright, use recordVideo instead. Enables video recording for all pages to videosPath folder. If videosPath is not existing folder, videosPath folder is created under ${OUTPUT_DIR}/browser/video/ folder. If videosPath is not specified, videos are not recorded.

videoSize is deprecated by playwright, use recordVideo instead. Specifies dimensions of the automatically recorded video. Can only be used if videosPath is set. If not specified the size will be equal to viewport. If viewport is not configured explicitly the video size defaults to 1280x720. Actual picture of the page will be scaled down if necessary to fit specified size.

  • Example {"width": 1280, "height": 720}

defaultBrowserType If no browser is open and New Context opens a new browser with defaults, it now uses this setting. Very useful together with Get Device keyword:

recordVideo enables video recording for all pages into a folder. If not specified videos are not recorded. Make sure to close context for videos to be saved. recordVideo is dictionary containing dir and size keys. If dir is not existing folder, videosPath folder is created under ${OUTPUT_DIR}/browser/video/ folder. size Optional dimensions of the recorded videos. If not specified the size will be equal to viewport. If viewport is not configured explicitly the video size defaults to 1280x720. Actual picture of each page will be scaled down if necessary to fit the specified size. size is dictionary containing width (Video frame width) and height (Video frame height) keys.

recordHar Enables HAR recording for all pages into to a file. Must be path to file, example ${OUTPUT_DIR}/har.file. If not specified, the HAR is not recorded. Make sure to await context to close for the to be saved.

omitContent: Optional setting to control whether to omit request content from the HAR. Default is False path: Path on the filesystem to write the HAR file to.

The ${OUTPUTDIR}/browser/ is removed at the first suite startup.

tracing is file name where the tracing file is saved. Example trace.zip will be saved to ${OUTPUT_DIR}/traces.zip. Temporary trace files will be saved to ${OUTPUT_DIR}/Browser/traces. If file name is defined, tracing will be enabled for all pages in the context. Tracing is automatically closed when context is closed. Temporary trace files will be automatically deleted at start of each test execution. Trace file can be opened after the test execution by running command from shell: rfbrowser show-trace -F /path/to/trace.zip.

screen Emulates consistent window screen size available inside web page via window.screen. Is only used when the viewport is set.

  • Example {'width': 414, 'height': 896}

storageState restores the storage stated created by the Save Storage State keyword. Must mbe full path to the file.

reduceMotion emulates prefers-reduced-motion media feature, supported values are reduce, no-preference.

forcedColors emulates forced-colors media feature, supported values are active and none.

Examples

Test an iPhone
    ${device}=    Get Device    iPhone X
    New Context    &{device}        # unpacking here with &
    New Page    http://example.com

A BrowserContext is the Playwright object that controls a single browser profile. Within a context caches and cookies are shared. See Playwright browser.newContext for a list of supported options.

If there's no open Browser this keyword will open one. Does not create pages.

Comment >>

New Page

Open a new Page.

Arguments

Argument Type Default value Description
urlstr, NoneNone

A Page is the Playwright equivalent to a tab. See Browser, Context and Page for more information about Page concept.

Returns NewPageDetails as dictionary for created page. NewPageDetails (dict) contains the keys page_id and video_path. page_id is a stable identifier for the created page. video_path is path to the created video or empty if video is not created.

When a New Page is called without an open browser, New Browser and New Context are executed with default values first.

url If specified it will open the new page to the specified URL.

Comment >>

New Persistent Context

Open a new persistent context.

Arguments

Argument Type Default value Description
userDataDirstr
browserSupportedBrowserschromium
headlessboolTrue
executablePathstr, NoneNone
argsList[str], NoneNone
ignoreDefaultArgsList[str], NoneNone
proxyProxy, NoneNone
downloadsPathstr, NoneNone
handleSIGINTboolTrue
handleSIGTERMboolTrue
handleSIGHUPboolTrue
timeouttimedelta0:00:30
envDict, NoneNone
devtoolsboolFalse
slowMotimedelta0:00:00
channelstr, NoneNone
acceptDownloadsboolTrue
ignoreHTTPSErrorsboolFalse
bypassCSPboolFalse
viewportViewportDimensions, NoneNone
userAgentstr, NoneNone
deviceScaleFactorfloat1.0
isMobileboolFalse
hasTouchboolFalse
javaScriptEnabledboolTrue
timezoneIdstr, NoneNone
geolocationGeoLocation, NoneNone
localestr, NoneNone
permissionsList[Permission], NoneNone
extraHTTPHeadersDict[str, str], NoneNone
offlineboolFalse
httpCredentialsHttpCredentials, NoneNone
colorSchemeColorScheme, NoneNone
videosPathstr, NoneNone
videoSizeViewportDimensions, NoneNone
defaultBrowserTypeSupportedBrowsers, NoneNone
hideRfBrowserboolFalse
recordVideoRecordVideo, NoneNone
recordHarRecordHar, NoneNone
tracingstr, NoneNone
screenDict[str, int], NoneNone
storageStatestr, NoneNone
reducedMotionReduceMotionno_preference
forcedColorsForcedColorsnone
urlstr, NoneNone

userDataDir Path to a User Data Directory, which stores browser session data like cookies and local storage. More details for Chromium and Firefox. Note that Chromium's user data directory is the parent directory of the "Profile Path" seen at chrome://version. Pass an empty string to use a temporary directory instead

If you want to use extensions you need to download the extension as a .zip, enable loading the extension, and load the extensions using chromium arguments like below. Extensions only work with chromium and with a headful browser.

${launch_args}=  Set Variable  ["--disable-extensions-except=./ublock/uBlock0.chromium", "--load-extension=./ublock/uBlock0.chromium"]
`New Persistent Context  browser=chromium  headless=False  args=${launch_args}

Check New Browser or New context for the specific argument docs.

Comment >>

Open Browser

Opens a new browser instance. Use this keyword for quick experiments or debugging sessions. Use New Page directly instead of Open Browser for production and automated execution. See Browser, Context and Page for more information about Browser and related concepts.

Arguments

Argument Type Default value Description
urlstr, NoneNone
browserSupportedBrowserschromium
headlessboolFalse
pause_on_failureboolTrue
bypassCSPTrue

Creates a new browser, context and page with specified settings. Only supports some of the settings Create _ Keywords do

url Navigates to URL if provided. Defaults to None.

browser Specifies which browser to use. The supported browsers are listed in the table below. The browser names are case-sensitive.

Value Name(s)
firefox Firefox
chromium Chromium
webkit webkit

headless If set to False, a GUI is provided otherwise it is hidden. Defaults to False.

pause_on_failure Stop execution when failure detected and leave browser open. Defaults to True.

bypassCSP Defaults to bypassing CSP and enabling custom script attach to the page.

Comment >>

Press Keys

Types the given key combination into element found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
keysstrnull

selector Selector of the text field. See the Finding elements section for details about the selectors.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Supports values like "a, b" which will be automatically typed. . Also supports identifiers for keys like ArrowLeft or Backspace. Using + to chain combine modifiers with a single keypress Control+Shift+T is supported.

See playwright's documentation for a more comprehensive list of supported input keys. Playwright docs for press.

Examples

# Keyword         Selector                    *Keys
Press Keys      //*[@id="username_field"]    h    e   l   o   ArrowLeft   l

Comment >>

Promise To

Wrap a Browser library keyword and make it a promise.

Arguments

Argument Type Default value Description
kwstrnull
argsnull

Promised keyword is executed and started on background. Test execution continues without waiting for kw to finish.

Returns reference to the promised keyword.

kw Keyword that will work async on background.

Examples

${promise}=     Promise To            Wait For Response     matcher=     timeout=3
Click           \#delayed_request
${body}=        Wait For              ${promise}

Comment >>

Promise To Upload File

Returns a promise that resolves when file from path has been uploaded.

Arguments

Argument Type Default value Description
pathPathLikenull

Fails if the upload has not happened during timeout.

Upload file from path into next file chooser dialog on page.

path Path to file to be uploaded.

Example use:

${promise}=    Promise To Upload File    ${CURDIR}/test_upload_file.txt
Click          id=open_file_chooser_button
${upload_result}=    Wait For    ${promise}

Alternatively, you can use Upload File By Selector keyword.

Comment >>

Promise To Wait For Download

Returns a promise that waits for next download event on page.

Arguments

Argument Type Default value Description
saveAsstr

If you can get the URL for the file to download, Download keyword should be a consistent way to download the file.

To enable downloads context's acceptDownloads needs to be true.

To configure download directory use New Browser's downloadsPath settings

With default filepath downloaded files are deleted when Context the download happened in is closed.

saveAs defines path where the file is saved. File will also temporarily be saved in playwright context's default download location.

Waited promise returns a dictionary which contains saveAs and suggestedFilename as keys. The saveAs contains where the file is downloaded and suggestedFilename contains the name suggested name for the download. The suggestedFilename is typically computed by the browser from the Content-Disposition response header or the download attribute. See the spec on whatwg. Different browsers can use different logic for computing it.

Example usage:

New Context          acceptDownloads=True
New Page             ${LOGIN_URL}
${dl_promise}          Promise To Wait For Download    /path/to/download/file.name
Click                \#file_download
${file_obj}=           Wait For  ${dl_promise}
File Should Exist    ${file_obj}[saveAs]
Should Be True       ${file_obj.suggestedFilename}

Comment >>

Record Selector

Record the selector that is under mouse.

Arguments

Argument Type Default value Description
labelstr, NoneNone

label text to show when on the box in the page while recording.

Focus on the page and move mouse over the element you want to select.

Examples

${selector} =    Record Selector   Button
Click  ${selector}
${selector2} =    Record Selector  Page header
Get Text  ${selector2}  ==  Expected text

Comment >>

Register Keyword To Run On Failure

Sets the keyword to execute, when a Browser keyword fails.

Arguments

Argument Type Default value Description
keywordstr, Nonenull
argsstrnull

keyword is the name of a keyword that will be executed if a Browser keyword fails. It is possible to use any available keyword, including user keywords or keywords from other libraries. args are the arguments to the keyword if any.

The initial keyword to use is set when importing the library, and the keyword that is used by default is Take Screenshot. Taking a screenshot when something failed is a very useful feature, but notice that it can slow down the execution.

It is possible to use string NONE or any other robot falsy name, case-insensitively, as well as Python None to disable this feature altogether.

This keyword returns an object which contains the the previously registered failure keyword. The return value can be always used to restore the original value later. The returned object contains keyword name and the possible arguments used to for the keyword.

Examples

Register Keyword To Run On Failure    Take Screenshot
${previous kw}=    Register Keyword To Run On Failure    NONE
Register Keyword To Run On Failure    ${previous kw}
Register Keyword To Run On Failure    Take Screenshot    fullPage=True
Register Keyword To Run On Failure    Take Screenshot    failure-{index}    fullPage=True

Comment >>

Reload

Reloads current active page.

Comment >>

Save Storage State

Saves the current active context storage state to a file.

Web apps use cookie-based or token-based authentication, where authenticated state is stored as cookies or in local storage. Keyword retrieves the storage state from authenticated contexts and save it to disk. Then New Context can be created with prepopulated state.

Please note state file may contains secrets and should not be shared with people outside of your organisation.

The file is created in ${OUTPUTDIR}/browser/state folder and file(s) are automatically deleted when new test execution starts. File path is returned by the keyword.

Examples

Test Case
    New context
    New Page    https://login.page.html
    #  Perform login
    Fill Secret    id=username    $username
    Fill Secret    id=password    $password
    Click    id=button
    Get Text    id=header    ==    Something
    #  Save storage to disk
    ${state_file} =    Save Storage State
    #  Create new context with saved state
    New context    storageState=${state_file}
    New Page    https://login.page.html
    #  Login is not needed because authentication is read from state file
    Get Text    id=header    ==    Something

Comment >>

Scroll By

Scrolls an element or the page relative from current position by the given values.

Arguments

Argument Type Default value Description
selectorstr, NoneNone
verticalstrheight
horizontalstr0
behaviorScrollBehaviorauto

selector Selector of the element. If the selector is ${None} or ${Empty} the page itself is scrolled. To ensure an element is in view use Hover instead. See the Finding elements section for details about the selectors.

vertical defines how far and in which direction to scroll vertically. It can be a positive or negative number. Positive scrolls down, like 50, negative scrolls up, like -50. It can be a percentage value of the absolute scrollable size, like 9.95% or negative like -10%. It can be the string height to defining to scroll exactly one visible height down or up with -height. Be aware that some pages do lazy loading and load more content once you scroll down. The percentage of the current scrollable height is used and may change.

horizontal defines where to scroll horizontally. Works same as vertical but defines positive values for right and negative values for left. width defines to scroll exactly one visible range to the right.

behavior defines whether the scroll happens directly or it scrolls smoothly.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Comment >>

Scroll To

Scrolls an element or the page to an absolute position based on given coordinates.

Arguments

Argument Type Default value Description
selectorstr, NoneNone
verticalstrtop
horizontalstrleft
behaviorScrollBehaviorauto

selector Selector of the element. If the selector is ${None} or ${Empty} the page itself is scrolled. To ensure an element is in view use Hover instead. See the Finding elements section for details about the selectors.

vertical defines where to scroll vertically. It can be a positive number, like 300. It can be a percentage value of the absolute scrollable size, like 50%. It can be a string defining that top or the bottom of the scroll area. < top | bottom > Be aware that some pages do lazy loading and load more content once you scroll down. Bottom defines the current known bottom coordinate.

horizontal defines where to scroll horizontally. Works same as vertical but defines < left | right > as start and end.

behavior defines whether the scroll happens directly or it scrolls smoothly.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Comment >>

Scroll To Element

This method waits for actionability checks, then tries to scroll element into view, unless it is completely visible.

Arguments

Argument Type Default value Description
selectorstrnull

selector Selector of the checkbox. See the Finding elements section for details about the selectors.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Does nothing if the element is already visible.

Comment >>

Select Options By

Selects options from select element found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
attributeSelectAttributenull
valuesnull

selector Selector of the select tag. See the Finding elements section for details about the selectors.

Returns list of options which keyword was able to select. The type of list item matches to attribute definition. Example if attribute equals to label returned list contains label values. Or in case of index it contains list of selected indexes.

Matches based on the chosen attribute with list of values. Possible attributes to match options by: attribute

Keyword uses strict mode, see Finding elements for more details about strict mode.

If no values to select are passed will deselect options in element.

Examples

${selected} =    Select Options By    select[name=preferred_channel]    label    Direct mail
List Should Contain Value    ${selected}    Direct mail
${selected} =    Select Options By    select[name=interests]    value    males    females    others
List Should Contain Value    ${selected}    males
List Should Contain Value    ${selected}    females
List Should Contain Value    ${selected}    others
Length Should Be    ${selected}    3
${selected} =    Select Options By    select[name=possible_channels]    index    0    2
List Should Contain Value    ${selected}    0
List Should Contain Value    ${selected}    2
${selected} =    Select Options By    select[name=interests]    text     Males    Females
List Should Contain Value    ${selected}    Males
List Should Contain Value    ${selected}    Females

Comment >>

SessionStorage Clear

Remove all saved data from the session storage.

Examples

SessionStorage Set Item    mykey3    myvalue3
 SessionStorage Clear
SessionStorage Get Item    mykey3    ==    ${None}

Comment >>

SessionStorage Get Item

Get saved data from from session storage.

Arguments

Argument Type Default value Description
keystrnull
assertion_operatorAssertionOperator, NoneNone
assertion_expectedAny, NoneNone

key Named key of the item in the storage.

See Assertions for further details for the assertion arguments. Defaults to None.

Examples

SessionStorage Set Item    key2    value2
${item} =    SessionStorage Get Item    key1
Should Be Equal    ${item}    value2

Comment >>

SessionStorage Remove Item

Remove saved data with key from the session storage.

Arguments

Argument Type Default value Description
keystrnull

key Name of the item which shall be deleted.

Examples

SessionStorage Set Item       mykey2    myvalue2
SessionStorage Remove Item    mykey2
SessionStorage Get Item       mykey2    ==    ${None}

Comment >>

SessionStorage Set Item

Save data to session storage.

Arguments

Argument Type Default value Description
keystrnull
valuestrnull

key The name of the key under which it should be saved.

value The value which shall be saved as a string.

Examples

SessionStorage Set Item    key2    value2

Comment >>

Set Assertion Formatters

Set keywords formatters for assertions.

Arguments

Argument Type Default value Description
formattersDict[str, List[str]]null

formatters is dictionary, where key is the keyword name where formatters are applied. Dictionary value is a list of formatter which are applied. Using keywords always replaces existing formatters for keywords.

Supported formatter are: normalize space, strip and apply to expected.

Examples

Set Assertion Formatters    {"Get Text": ["strip", "normalize spaces"]}
${value} =    Get Text    //div    ==    ${SPACE}Expected${SPACE * 2}Text
Should Be Equal    ${value}    Expected Text

Set Browser Timeout

Sets the timeout used by most input and getter keywords.

Arguments

Argument Type Default value Description
timeouttimedeltanull

timeout Timeout of it is for current playwright context and for new contexts. Supports Robot Framework time format . Returns the previous value of the timeout.

Examples

${old_timeout} =    Set Browser Timeout    1m 30 seconds
Click     //button
Set Browser Timeout    ${old_timeout}

Comment >>

Set Geolocation

Updated the correct Context's geolocation.

Arguments

Argument Type Default value Description
latitudefloatnull
longitudefloatnull
accuracyfloat, NoneNone

Latitude can be between -90 and 90 and longitude can be between -180 and 180. Accuracy of the location must be positive number and defaults to 0. When creating context, grant geolocation permission for pages to read its geolocation.

Examples

${permissions} =    Create List    geolocation
New Context    permissions=${permissions}
Set Geolocation    60.173708, 24.982263    3    # Points to Korkeasaari in Helsinki.

Comment >>

Set Offline

Toggles current Context's offline emulation.

Arguments

Argument Type Default value Description
offlineboolTrue

offline Toggles the offline mode. Set to False to switch back to online mode. Defaults to True.

Comment >>

Set Retry Assertions For

Sets the timeout used in retrying assertions when they fail.

Arguments

Argument Type Default value Description
timeouttimedeltanull

Set Browser timeout controls how long Playwright will perform waiting in the node side, assertion retry will determine how long Browser library will retry the playwright operation. Generally assertion timeout should be longer than the timeout set by Set Browser timeout.

Returns the previous value of the assertion retry.

Examples

Set Browser Timeout    10 seconds
${old} =    Set Retry Assertions For    30s
Get Title    ==    Login Page
Set Retry Assertions For    ${old}

Example waits 10 seconds on Playwright to get the page title and library will retry 30 seconds to make sure that title is correct.

Comment >>

Set Strict Mode

Controls library strict mode.

Arguments

Argument Type Default value Description
modeboolnull

When set to True, keywords that are searching elements will use Playwright strict mode. Keyword changes library strict mode value and keyword also return the previous strict mode value.

This setting is global and will impact every test/task and suite after.

Examples

${old_mode} =      Set Strict Mode    False
Get Text           //input            # Does not fail if selector points to one or more elements
Set Strict Mode    ${old_mode}

Comment >>

Set Viewport Size

Sets current Pages viewport size to specified dimensions.

Arguments

Argument Type Default value Description
widthintnull
heightintnull

In the case of multiple pages in a single browser, each page can have its own viewport size. However, New Context allows to set viewport size (and more) for all later opened pages in the context at once.

Set Viewport Size will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size before navigating to the page with New Context before opening the page itself.

width Sets the width size.

height Sets the height size.

Comment >>

Switch Browser

Switches the currently active Browser to another open Browser.

Arguments

Argument Type Default value Description
idstrnull

Returns a stable identifier for the previous browser. See Browser, Context and Page for more information about Browser and related concepts.

id Id of the browser to be changed to. Starting at 0.

Comment >>

Switch Context

Switches the active BrowserContext to another open context.

Arguments

Argument Type Default value Description
idstrnull
browserstrCURRENT

Returns a stable identifier for the previous context. See Browser, Context and Page for more information about Context and related concepts.

id of the context to be changed to. Randomly generated UUID.

browser < CURRENT | ALL | str> Switch context in specified browser. If value is not "CURRENT" or "ALL" it shall be the id of the browser where to switch context.

Examples

${first_context} =     New Context
New Page             ${URL1}
${second_context} =    New Context
New Page             ${URL2}
Switch Context       ${first_context}    # Switches back to first context and page.

Comment >>

Switch Page

Switches the active browser page to another open page by id or NEW.

Arguments

Argument Type Default value Description
idNewPageDetails, strnull
contextstrCURRENT
browserstrCURRENT

Returns a stable identifier id for the previous page. See Browser, Context and Page for more information about Page and related concepts.

id < CURRENT | NEW | str | NewPageDetails > Id of the page to be changed to or

NEW for a page opened after the current page. This may timeout if no new pages exists before library timeout. See Set Browser Timeout for how to change the timeout.

With CURRENT you can get the id of the "CURRENT" page

context < CURRENT | str> Switch page in specified context. If value is not "CURRENT" it should be the id of the context where to switch page.

browser < CURRENT | str> Switch page in specified browser. If value is not "CURRENT" it should be the id of the browser where to switch page.

Examples

Click           button#pops_up    # Open new page
${previous} =    Switch Page      NEW

Comment >>

Take Screenshot

Takes a screenshot of the current window or element and saves it to disk.

Arguments

Argument Type Default value Description
filenamestrrobotframework-browser-screenshot-{index}
selectorstr, NoneNone
fullPageboolFalse
fileTypeScreenshotFileTypespng
qualityint, NoneNone
timeouttimedelta, NoneNone
cropBoundingBox, NoneNone
disableAnimationsboolFalse
maskList[str], str
omitBackgroundboolFalse

filename Filename into which to save. The file will be saved into the robot framework ${OUTPUTDIR}/browser/screenshot directory by default, but it can overwritten by providing custom path or filename. String {index} in filename will be replaced with a rolling number. Use this to not override filenames. If filename equals to EMBED (case insensitive), then screenshot is embedded as Base64 image to the log.html. The image is saved temporally to the disk and warning is displayed if removing the temporary file fails.

The ${OUTPUTDIR}/browser/ is removed at the first suite startup.

selector Take a screenshot of the element matched by selector. See the Finding elements section for details about the selectors. If not provided take a screenshot of current viewport.

fullPage When True, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to False.

fileType <"png"|"jpeg"> Specify screenshot type, defaults to png.

quality The quality of the image, between 0-100. Not applicable to png images.

timeout Maximum time how long taking screenshot can last, defaults to library timeout. Supports Robot Framework time format, like 10s or 1 min, pass 0 to disable timeout. The default value can be changed by using the Set Browser Timeout keyword.

crop Crops the taken screenshot to the given box. It takes same dictionary as returned from Get BoundingBox. Cropping only works on page screenshot, so if no selector is given.

disableAnimations When set to True, stops CSS animations, CSS transitions and Web Animations. Animations get different treatment depending on their duration:

  • finite animations are fast-forwarded to completion, so they'll fire transitionend event.
  • infinite animations are canceled to initial state, and then played over after the screenshot.

mask Specify selectors that should be masked when the screenshot is taken. Masked elements will be overlayed with a pink box #FF00FF that completely covers its bounding box. Arguemnt can take a single selector string or a list of selector strings if multiple different elements should be masked.

omitBackground Hides default white background and allows capturing screenshots with transparency. Not applicable to jpeg images.

Keyword uses strict mode if selector is defined. See Finding elements for more details about strict mode.

Example

Take Screenshot                                 # Takes screenshot from page with default filename
Take Screenshot   selector=id=username_field    # Captures element in image
# Takes screenshot with jpeg extension, defines image quality and timeout how long taking screenhost should last
Take Screenshot   fullPage=True    fileType=jpeg    quality=50    timeout=10s

Comment >>

Type Secret

Types the given secret from variable_name into the text field found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
secretstrnull
delaytimedelta0:00:00
clearboolTrue

This keyword does not log secret in Robot Framework logs, if keyword resolves the variable value internally. If enable_playwright_debug is enabled in the library import, secret will be always visible as plain text in the playwright debug logs, regardless of the Robot Framework log level.

selector Selector of the text field. See the Finding elements section for details about the selectors.

secret Environment variable name with % prefix or a local variable with $ prefix that has the secret text value. Variable names can be used with and without curly braces.

delay Delay between the single key strokes. It may be either a number or a Robot Framework time string. Time strings are fully explained in an appendix of Robot Framework User Guide. Defaults to 0 ms. Example: 50 ms

clear Set to false, if the field shall not be cleared before typing. Defaults to true.

Keyword uses strict mode, see Finding elements for more details about strict mode.

See Type Text for details.

Example

Type Secret    input#username_field    $username      # Keyword resolves ${username} variable value from Robot Framework variables
Type Secret    input#username_field    %username      # Keyword resolves $USERNAME/%USERNAME% variable value from environment variables
Type Secret    input#username_field    ${username}    # Robot Framework resolves the variable value, but secrect can leak to Robot framework output files.

Comment >>

Type Text

Types the given txt into the text field found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
txtstrnull
delaytimedelta0:00:00
clearboolTrue

Sends a keydown, keypress/input, and keyup event for each character in the text.

selector Selector of the text field. See the Finding elements section for details about the selectors.

txt Text for the text field.

delay Delay between the single key strokes. It may be either a number or a Robot Framework time string. Time strings are fully explained in an appendix of Robot Framework User Guide. Defaults to 0 ms. Example: 50 ms

clear Set to false, if the field shall not be cleared before typing. Defaults to true.

Keyword uses strict mode, see Finding elements for more details about strict mode.

See Fill Text for direct filling of the full text at once.

Example

Type Text    input#username_field    user
Type Text    input#username_field    user    delay=10 ms    clear=No

Comment >>

Uncheck Checkbox

Unchecks the checkbox found by selector.

Arguments

Argument Type Default value Description
selectorstrnull
forceboolFalse

selector Selector of the checkbox. See the Finding elements section for details about the selectors.

force Set to True to skip Playwright's Actionability checks.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Does nothing if the element is not checked/selected.

Comment >>

Upload File By Selector

Uploads file from path to file input element matched by selector.

Arguments

Argument Type Default value Description
selectorstrnull
pathPathLikenull

Fails if upload is not done before library timeout.

Examples

Upload File By Selector    //input[@type='file']    big_file.zip

Comment >>

Wait For

Waits for promises to finish and returns results from them.

Arguments

Argument Type Default value Description
promisesFuturenull

Returns one result if one promise waited. Otherwise returns an array of results. If one fails, then this keyword will fail.

See Promise To for more information about promises.

For general waiting of elements please see Implicit waiting.

promises Work in progress

Examples

${promise}=    Promise To            Wait For Response     matcher=     timeout=3
Click         \#delayed_request
${body}=       Wait For              ${promise}

Comment >>

Wait For Alert

Handle next dialog on page with action as promise.

Arguments

Argument Type Default value Description
actionDialogActionnull
prompt_inputstr
textstr, NoneNone

See Handle Future Dialogs for more details about action and what types of dialogues are supported.

The main difference between this keyword and Handle Future Dialogs is that Handle Future Dialogs keyword is automatically set as promise. But this keyword must be called as argument to Promise To keyword. Also this keyword can optionally verify the dialogue text and return it. If text is argument None or is not set, dialogue text is not verified.

Example with returning text:

${promise} =         Promise To    Wait For Alert    action=accept
Click              id=alerts
${text} =            Wait For      ${promise}
Should Be Equal      ${text}         Am an alert

Example with text verify:

${promise} =       Promise To    Wait For Alert    action=accept    text=Am an alert
Click              id=alerts
${text} =          Wait For      ${promise}

Comment >>

Wait For All Promises

Waits for all promises to finish.

If one promises fails, then this keyword will fail.

Examples

Promise To               Wait For Response     matcher=     timeout=3
Click                    \#delayed_request
Wait For All Promises

Comment >>

Wait For Elements State

Waits for the element found by selector to satisfy state option.

Arguments

Argument Type Default value Description
selectorstrnull
stateElementStatevisible
timeouttimedelta, NoneNone
messagestr, NoneNone

Note that Browser library has Implicit waiting mechanisms. Depending on the situation you might not need to use Wait for Elements State.

State options could be either appear/disappear from dom, or become visible/hidden. If at the moment of calling the keyword, the selector already satisfies the condition, the keyword will return immediately.

If the selector doesn't satisfy the condition within the timeout the keyword will FAIL.

selector Selector of the corresponding object. See the Finding elements section for details about the selectors.

state See ElementState for explanation.

Note that element without any content or with display:none has an empty bounding box and is not considered visible.

timeout uses default timeout from library if not set.

message overrides the default error message. The message argument accepts {selector}, {function}, and {timeout} format options. The {function} formatter is same state argument value.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Examples

Wait For Elements State    //h1    visible    timeout=2 s
Wait For Elements State    //hi    focused    1s

Comment >>

Wait For Function

Polls JavaScript expression or function in browser until it returns a (JavaScript) truthy value.

Arguments

Argument Type Default value Description
functionstrnull
selectorstr
pollingstr, timedeltaraf
timeouttimedelta, NoneNone
messagestr, NoneNone

function A valid javascript function or a javascript function body. For example () => true and true will behave similarly.

selector Selector to resolve and pass to the JavaScript function. This will be the first argument the function receives. If given a selector a function is necessary, with an argument to capture the elementhandle. For example (element) => document.activeElement === element See the Finding elements section for details about the selectors.

polling Default polling value of "raf" polls in a callback for requestAnimationFrame. Any other value for polling will be parsed as a robot framework time for interval between polls.

timeout Uses default timeout of 10 seconds if not set.

message overrides the default error message. The message argument accepts {selector}, {function}, and {timeout} format options.

Keyword uses strict mode, see Finding elements for more details about strict mode.

Example usage:

${promise}      Promise To      Wait For Function    element => element.style.width=="100%"    selector=\#progress_bar    timeout=4s
Click         \#progress_bar
Wait For      ${promise}

Comment >>

Wait For Navigation

Waits until page has navigated to given url.

Arguments

Argument Type Default value Description
urlstrnull
timeouttimedelta, NoneNone
wait_untilPageLoadStatesload

url expected navigation target address either the exact match or a JavaScript-like regex wrapped in / symbols.

timeout Timeout in milliseconds. Uses default timeout of 10 seconds if not set.

wait_until <"load"|"domcontentloaded"|"networkidle|"commit""> When to consider operation succeeded, defaults to load. Events can be either: 'domcontentloaded' - consider operation to be finished when the DOMContentLoaded event is fired. 'load' - consider operation to be finished when the load event is fired. 'networkidle' - consider operation to be finished when there are no network connections for at least 500 ms. commit - consider operation to be finished when network response is received and the document started loading.

Keyword works only when page is loaded and does not work if URL fragment changes. Example if https://marketsquare.github.io/robotframework-browser/Browser.html changes to https://marketsquare.github.io/robotframework-browser/Browser.html#Wait%20For%20Navigation keyword will fail.

Examples

Go To                  ${ROOT_URL}/redirector.html
Wait for navigation    ${ROOT_URL}/posted.html    wait_until=${wait_until}

Comment >>

Wait For Request

Waits for request matching matcher to be made.

Arguments

Argument Type Default value Description
matcherstr
timeouttimedelta, NoneNone

matcher Request URL string, JavaScript regex or JavaScript function to match request by. By default (with empty string) matches first available request. For additional information, see the Playwright waitForRequest documentation.

timeout Timeout supports Robot Framework time format. Uses default timeout if not set.

Examples

Click               \#delayed_request
Wait For Request    timeout=1s

Async Example:

${promise} =    Promise To         Wait For Request    matcher=\\/\\/local\\w+\\:\\d+\\/api    timeout=3s
Click         \#delayed_request
Wait For      ${promise}

JavaScript Function Example:

Click               \#delayed_request    # Creates response which should be waited before pressing save.
Wait For Request    request => request.url().endsWith('api/get/json') && request.method() === 'GET'

Comment >>

Wait For Response

Waits for response matching matcher and returns python dict with contents.

Arguments

Argument Type Default value Description
matcherstr
timeouttimedelta, NoneNone

matcher Request URL string, JavaScript regex or JavaScript function to match request by. By default (with empty string) matches first available request. For additional information, see the Playwright waitForResponse documentation.

timeout Timeout in seconds. Uses default timeout if not set.

The response is a Python dictionary with following attributes:

  • status <int> The status code of the response.
  • statusText <str> Status text corresponding to status, e.g OK or INTERNAL SERVER ERROR.
  • body <dict | str> The response body. If the body can be parsed as a JSON obejct, it will be returned as Python dictionary, otherwise it is returned as a string.
  • headers <dict> A dictionary containing all response headers.
  • ok <bool> Whether the request was successfull, i.e. the status is range 200-299.
  • request <dict> containing method <str>, headers <dict> and postData <dict> | <str>
  • url <str> url of the request.

Synchronous Example:

Click                \#delayed_request    # Creates response which should be waited before next actions
Wait For Response    matcher=\\/\\/local\\w+\\:\\d+\\/api
Click                \#save

Asynchronous Example:

${promise} =    Promise To    Wait For Response    timeout=60s
Click           \#delayed_request    # Creates response which should be waited before pressing save.
Click           \#next
Wait For        ${promise}            # Waits for the response
Click           \#save

JavaScript Function Example:

Click               \#delayed_request    # Creates response which should be waited before pressing save.
Wait For Response   response => response.url().endsWith('json') && response.request().method() === 'GET'

Comment >>

Wait Until Network Is Idle

Waits until there has been at least one instance of 500 ms of no network traffic on the page after loading.

Arguments

Argument Type Default value Description
timeouttimedelta, NoneNone

Doesn't wait for network traffic that wasn't initiated within 500ms of page load.

timeout Timeout supports Robot Framework time format. Uses default timeout of 10 seconds if not set.

Examples

Go To                         ${URL}
Wait Until Network Is Idle    timeout=3s

Comment >>