BROWSER
Documentation— open the keyword list

152 keywords

Everything in the Browser library, generated from the library itself. Every argument type links to what it accepts, and every keyword links back from the types that use it.

Browser 20.4.020 modules83 argument types

Introduction

Generated from the library's Libdoc for 20.4.0. The original is at Browser.html.

Browser library is a browser automation library for Robot Framework.

This is the keyword documentation for Browser library. For installation, guides and everything else, see robotframework-browser.org. For more information about Robot Framework itself, see robotframework.org.

Browser library uses Playwright Node module to automate Chromium, Firefox and WebKit with a single library.

Table of contents

Browser, Context and Page

Browser library works in three layers that build on each other.

Layer Is Opened with
Browser A browser process: chromium, firefox or webkit. New Browser
Context An isolated session in that process: its own cookies, storage and permissions. Contexts share nothing with each other. New Context
Page A tab, with its own content and history. Selectors resolve here. New Page

Playwright brings its own browser binaries, so no separate driver is needed. A browser starts headless unless New Browser's headless argument is set to False.

Engine Ships in
chromium Google Chrome, Microsoft Edge, Opera
firefox Mozilla Firefox
webkit Safari on macOS and iOS

The layers fill themselves in downwards: New Page with nothing open starts a browser and a context first, using defaults. Open Browser opens all three at once and is meant for experiments and debugging rather than for suites.

A context is the cheap unit of isolation — opening one is roughly a thousand times cheaper than starting a browser, so a clean session per test does not mean a new process. Context-level settings include viewport, geolocation, locale, colorScheme and httpCredentials; downloads are accepted unless acceptDownloads=False is given.

Each browser, context and page has an id. Get Browser Catalog returns everything currently open.

Which layer to open for which job, and the cost of each: https://robotframework-browser.org/docs/concepts/browser-context-page

Automatic page and context closing

Controls when contexts and pages are closed during the test execution.

If automatic closing level is TEST, contexts and pages that are created during a single test are automatically closed when the test ends. Contexts and pages that are created during suite setup are closed when the suite teardown ends.

If automatic closing level is SUITE, all contexts and pages that are created during the test suite are closed when the suite teardown ends.

If automatic closing level is MANUAL, nothing is closed automatically while the test execution is ongoing. All browsers, context and pages are automatically closed when test execution ends.

If automatic closing level is KEEP, nothing is closed automatically while the test execution is ongoing. Also, nothing is closed when test execution ends, including the node process. Therefore, it is users responsibility to close all browsers, context and pages and ensure that all process that are left running after the test execution end are closed. This level is only intended for test case development and must not be used when running tests in CI or similar environments.

Automatic closing can be configured or switched off with the auto_closing_level library import parameter.

See: Importing

Finding elements

Keywords that act on an element take a selector argument. A selector is one or more clauses, each naming a strategy, chained with >>.

Under strict mode a selector matching more than one element fails the keyword. It is on by default, changeable in the library importing or with Set Strict Mode, and each keyword's documentation states whether it applies.

Strategies

Strategy Matches on Example
role ARIA role, with optional accessible name. role=button[name="Login"]
data-testid data-testid attribute. data-testid=login
text Text content. See Text matching. text=Login
id Element ID attribute. id=login_btn
css CSS selector. css=.class > \#login_btn
xpath XPath expression. xpath=//input[@id="login_btn"]
data-test-id data-test-id attribute. data-test-id=login
data-test data-test attribute. data-test=login
css:light As css, but does not pierce shadow DOM. css:light=.class

An attribute engine is equivalent to the matching css attribute selector: data-test-id=foo is css=[data-test-id="foo"].

css:light is the only non-piercing engine still supported. All other locator, except xpath, pierce shadow DOM automatically.

Two filters narrow what a clause already matched. Filter order changes the result.

Filter Selects Example
nth The nth match, zero based. 0 first, -1 last. css=button >> nth=1
visible Only visible, or only hidden, matches. css=button >> visible=true

Playwright's CSS pseudo-classes (:has(), :has-text(), :nth-match()) and its layout selectors (:right-of(), :below()) are available inside a css clause. Which strategy to prefer, and the full list with examples: https://robotframework-browser.org/docs/concepts/selectors

Explicit and implicit strategy

A strategy is named with a strategy=value prefix. Spaces around the separator are ignored, so css=foo, css= foo and css = foo are the same.

Without a prefix the strategy is inferred:

Selector starts with Read as Example
// or .. xpath //span/button is xpath=//span/button
" or ' text, exact "Login" is text="Login"
anything else css span > button is css=span > button

Because # starts a comment in Robot Framework data, an id selector must be escaped as \#id.

css follows the CSS selector specification and xpath the XPath specification; neither is re-documented here.

Text matching

The text engine matches a text node, and the value of button and submit inputs. In keywords that insert text it also matches a field by its label.

Form Matches
text=Login Substring, case-insensitive, leading and trailing whitespace ignored.
text="Login " Exact: case, whitespace and all. Escape a quote as \".
text=/^Hi .*!$/i JavaScript-style regular expression with flags: e.g. i for case-insensitive.

Chaining

Clauses are separated by >> and each searches inside the result of the previous one. The chain returns what the last clause matched; prefix a clause with * to return that one instead. A value containing >> must be quoted, as in text="some >> text".

Click    css=.checkout >> text=ConfirmGet Element    *css=article >> text=Hello    # returns the article

iFrames

A chain does not cross a frame boundary. >>> combines a selector for the frame element with a selector inside it; the clause immediately before >>> must select the frame itself.

Click    id=iframe >>> id=btn

For several keywords inside one frame, set a prefix with Set Selector Prefix.

Shadow DOM

All engines, except css:light and xpath, pierce open shadow roots automatically: every descendant combinator, including the implicit one at the start of a selector, crosses any number of them. Light DOM is searched first, then open shadow roots, in document order. Closed shadow roots and iframes are never entered.

Use css:light to stop at the shadow boundary. Worked examples of what each matches: https://robotframework-browser.org/docs/concepts/selectors

Element references

Get Element returns a selector string for what it matched, and Get Elements returns a list of them. They are ordinary selectors, so they go in the first clause of another selector, chained with >>:

${ref}=    Get Element    .some_class           Click          ${ref} >> .some_child           Click          ${ref} >> .other_child

Clauses after the reference are relative to it. Because the value is a selector rather than a captured DOM node, it is resolved from the page again on every use. A reference works like any other first clause, >>> included: if it points at an iframe, ${ref} >>> h1 crosses into it.

Assertions

Keywords taking assertion_operator <AssertionOperator> and assertion_expected can assert on the value they return, and still return it. An assertion retries until it passes or retry_assertions_for expires; see Importing for that setting, which defaults to 1 second.

Currently supported assertion operators are:

Operator Alternative Operators Description Validate Equivalent
== equal, equals, should be Checks if returned value is equal to expected value. value == expected
!= inequal, should not be Checks if returned value is not equal to expected value. value != expected
> greater than Checks if returned value is greater than expected value. value > expected
>= Checks if returned value is greater than or equal to expected value. value >= expected
< less than Checks if returned value is less than expected value. value < expected
<= Checks if returned value is less than or equal to expected value. value <= expected
*= contains Checks if returned value contains expected value as substring. expected in value
not contains Checks if returned value does not contain expected value as substring. expected in value
^= should start with, starts Checks if returned value starts with expected value. re.search(f"^{expected}", value)
$= should end with, ends Checks if returned value ends with expected value. re.search(f"{expected}$", value)
matches Checks if given RegEx matches minimum once in returned value. re.search(expected, value)
validate Checks if given Python expression evaluates to True.
evaluate then When using this operator, the keyword does return the evaluated Python expression.

There are three different possibilities what keyword returns when matches operator is used: string, tuple or dictionary. What keyword returns depends on how the RegEx is formed. If RegEx does not contain group(s), then keyword will return the string without modifications. If RegEx contains groups, meaning (...), then keyword will return a tuple. Each tuple item contains the text which is matched by the group. If there is group and group has a name, (?P<name>...) syntax, then keyword returns a dictionary. In this case dictionary key is the group name and value contains the matched text. If there mix of groups and groups with names, then tuple is returned.

Currently supported formatters for assertions are:

Formatter Description
normalize spaces Substitutes multiple spaces to single space from the value
strip Removes spaces from the beginning and end of the value
case insensitive Converts value to lower case before comparing
apply to expected Applies rules also for the expected value

Formatters are applied to the value before assertion is performed and keywords returns a value where rule is applied. Formatter is only applied to the value which keyword returns and not all rules are valid for all assertion operators. If apply to expected formatter is defined, then formatters are then formatter are also applied to expected value.

Expected values are generally used as given, so they must already have the type returned by the keyword. Keywords returning numbers are an exception and convert the expected value.

Examples:

Comparing strings with < or > compares code points character by character and stops at the first difference; length is never considered. Example: A < Z, Z < a, ac < dc, 'abcde' < 'abd'.

validate takes a Python expression over value. then and evaluate do not assert: they return the result of an expression over value.

Get Text             h1      validate    value.startswith("Welcome")${id}=    Get Property    a#link    href    then    value.split("/")[-1]

A failing assertion has a default message, replaceable with message. It accepts the format fields {value}, {expected}, {value_type} and {expected_type}.

What each operator is for, why a type mismatch is the usual failure, and the formatters that normalise a value before comparison: https://robotframework-browser.org/docs/concepts/assertions

Implicit waiting

Browser library and Playwright have many mechanisms to help in waiting for elements. Playwright will auto-wait before performing actions on elements. Please see Auto-waiting on Playwright documentation for more information.

On top of Playwright auto-waiting Browser assertions will wait and retry for specified time before failing any Assertions. Time is specified in Browser library initialization with retry_assertions_for.

Browser library also includes explicit waiting keywords such as Wait for Elements State if more control for waiting is needed.

Experimental: Re-using same node process

The Node.js side can be started as a standalone process and shared by every Browser library running on the same machine, instead of each one starting its own. This can speed up parallel runs. Start it from the directory where the Browser package is installed with ` PLAYWRIGHT_BROWSERS_PATH=0 node Browser/wrapper/index.js HOST PORT ` , for example ... index.js 127.0.0.1 12345. Both arguments are required: the script reads the host first and exits with No port defined if only one is given. Point runs at it with the playwright_process_port import parameter or the ROBOT_FRAMEWORK_BROWSER_NODE_PORT environment variable, for example ROBOT_FRAMEWORK_BROWSER_NODE_PORT=PORT pabot ...

What this costs, how to run it under Pabot, and how to pass Node flags such as --inspect: https://robotframework-browser.org/docs/operations/node-process

Scope Setting

Some keywords which manipulates library settings have a scope argument. With that scope argument one can set the "live time" of that setting. Available Scopes are: Global, Suite and `Test/Task See Scope`. Is a scope finished, this scoped setting, like timeout, will no longer be used.

Live Times:

  • A Global scope will live forever until it is overwritten by another Global scope. Or locally temporarily overridden by a more narrow scope.
  • A Suite scope will locally override the Global scope and live until the end of the Suite within it is set, or if it is overwritten by a later setting with Global or same scope. Children suite does inherit the setting from the parent suite but also may have its own local Suite setting that then will be inherited to its children suites.
  • A Test or Task scope will be inherited from its parent suite but when set, lives until the end of that particular test or task.

A new set higher order scope will always remove the lower order scope which may be in charge. So the setting of a Suite scope from a test, will set that scope to the robot file suite where that test is and removes the Test scope that may have been in place.

Using Browser from Python

Browser keywords can be called directly from Python, from your own Robot Framework library. Arguments convert the same way Robot Framework converts them, so browser.click("//button", "middle") works, and a Python None is passed through unchanged. Robot Framework's own features do not all follow: Automatic page and context closing and Scope Setting need Browser's listener to be registered, and run_on_failure never applies to a keyword your library calls from Python.

Getting started, and what your own library gets in each case: https://robotframework-browser.org/docs/extending/python-libraries

Language

Keyword names and their documentation can be translated. Install a Python package whose name starts with robotframework_browser_translation and set the language import parameter to the language that the package declares; Browser discovers it on the module search path through the Python plugin API.

A template for a new translation, containing every keyword in the correct format, is produced by rfbrowser translation /path/to/translation.json. Keywords coming from library plugins and JavaScript extensions can be included with the --plugings and --jsextension arguments.

Writing and packaging a translation: https://robotframework-browser.org/docs/extending/translations

ENVIRONMENT VARIABLES

These environment variables modify the behaviour of the library. Two of them are development features and must not be set in production; they are listed here so that nobody uses them by accident.

Environment variable Description
ROBOT_FRAMEWORK_BROWSER_NODE_PORT Port number for connecting to an existing node process. This is an alternative to playwright_process_port import argument.
ROBOT_FRAMEWORK_BROWSER_NODE_COVERAGE If set to 1, will collect code coverage for the node process. This must not be used in production environments and is not supported on Windows.
ROBOT_FRAMEWORK_BROWSER_NODE_DEBUG_OPTIONS Debug options for the node process. This is a comma-separated list of arguments, for example --inspect. This must not be used in production environments.

Which of these to prefer over an import parameter, and how they behave with BrowserBatteries: https://robotframework-browser.org/docs/operations/environment-variables

Keywords 152

Add Locator Handler Click

Add a handler function which will activate when selector is visible and click.

Arguments

NameDefaultType
selectorrequiredstr
click_selectorrequiredstr
noWaitAfternamed only=Truebool
timesnamed only=NoneUnion
click_clickCountnamed only=1int
click_delaynamed only=0int
click_forcenamed only=Falsebool

Tags

PageContentSetter

Documentation

Add a handler function which will activate when selector is visible and click.

The handler will click the element indicated by click_selector.

When testing a web page, sometimes unexpected overlays, for example an "Accept Cookies" dialog, might appear and block the interaction with the page, like the Click keyword. These overlays can be problematic to handle, because they might appear randomly in the page. This keyword allows to create an automatic method, which will close those overlays by clicking the element indicated by click_selector. The handler is activated when the element indicated by selector is visible. For further information, see Playwright's addLocatorHandler method.

Arguments Description
selector Is the selector to the element which indicates that the locator handler should be called.
noWaitAfter Defaults to True, which means that the overlay may stay visible after the handler has run. If set to False, Playwright waits until the overlay becomes hidden, and only then the library continues with the action/assertion that triggered the handler.
times Is how many times the locator handler is called. None, the default, means unlimited.
click_selector Is the selector to the element to be clicked.
click_clickCount Is the number of times to click the element. Defaults to 1.
click_delay Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.
click_force Whether to bypass checks and dispatch the event directly. Defaults to false.

The arguments click_selector, click_clickCount, click_delay and click_force correspond to the arguments of the Click With Options keyword, but click_delay is given as a plain number of milliseconds. The selector, noWaitAfter and times are for the locator handler. The handler is tied to the active page, if there is need to add handler to another page, this keyword needs to be called separately for each page. If the times argument is set to a positive value, the locator handler is removed after the handler has been called the specified number of times.

Example add locator handler to click button with id="ButtonInOverlay" when id=Overlay is visible:

New Page    ${URL}Add Locator Handler Click    id=Overlay    id=ButtonInOverlay     # Add locator handler to pageType Text    id:username    user    # If element with id=Overlay appears, the handler will click the button id=ButtonInOverlayType Text    id:password    password    # Or if overlay is visible here, then handler is called hereClick    id:loginRemove Locator Handler    id=Overlay    # Removes the locator handler from page

Locator Handlers, line 24

Add Locator Handler Custom

Add a handler function which will activate when selector is visible and performs handler specification.

Arguments

NameDefaultType
selectorrequiredstr
handler_specrequiredlist
noWaitAfter=Truebool
times=NoneUnion

Tags

PageContentSetter

Documentation

Add a handler function which will activate when selector is visible and performs handler specification.

When the element indicated by selector is visible, the handler will perform the actions specified in the handler_spec.

Arguments Description
selector Is the selector to the element which indicates that the locator handler should be called.
handler_spec Is a list of dictionaries which defines the actions to be performed.
noWaitAfter Defaults to True, which means that the overlay may stay visible after the handler has run. If set to False, Playwright waits until the overlay becomes hidden, and only then the library continues with the action/assertion that triggered the handler.
times Is how many times the locator handler is called. None, the default, means unlimited.

The handler_spec is a list of dictionaries, where each dictionary defines one action. The dictionary must contain the key action which defines the action to be performed. The action can be one of the following: click, fill, check and uncheck. Action is also case insensitive. The dictionary must also contain the key selector which defines the element to be interacted with. The fill action must also contain the key value which defines the value to be filled in the element. For the other actions the key value must not be defined. Additional keys are passed to the action as keyword arguments. For example for the click action refer to Playwright's documentation to see which options are possible.

The selectors in the handler_spec are not resolved in strict mode. If a selector matches more than one element, the first matching element is used. If an action in the handler fails, the error is only logged on the Browser library node side and the keyword which triggered the handler does not fail because of it.

The selector, noWaitAfter and times are for the locator handler method. The handler is tied to the active page, if there is need to add handler to another page, this keyword needs to be called separately for each page. If the times argument is set to a positive value, the locator handler is removed after the handler has been called the specified number of times.

Running the handler will alter your page state mid-test. For example it will change the currently focused element and move the mouse. Make sure that keywords that run after the handler are self-contained and do not rely on the focus and mouse state being unchanged.

Please note that the automatic argument conversion is not done for the handler_spec dictionary. This is because Robot Framework does not convert values inside the dictionary that are actually arguments to a separate Playwright API call. Therefore the user is responsible for converting the values to the correct type. For example if a timeout is needed, the value must be converted to a number on the Robot Framework test data side.

Example adds locator handler to fill input id=overlayInput with value "Hello" and click element id=OverlayCloseButton when id=Overlay is visible:

New Page    ${URL}VAR    &{handler_spec_fill}...    action=Fill...    selector=id=overlayInput...    value=HelloVAR    &{handler_spec_click}...    action=click...    selector=id=OverlayCloseButtonAdd Locator Handler Custom...    id=overlay...    [${handler_spec_fill}, ${handler_spec_click}]Type Text    id:username    user    # If element with id=overlay appears, the handler fills id=overlayInput and clicks id=OverlayCloseButtonType Text    id:password    password    # Or if overlay is visible here, then handler is called hereClick    id:login

Example with click and different options and types:

VAR    &{handler_spec}...    action=CLICK    # Action is case insensitive...    selector=id=OverlayCloseButton...    button=left...    clickCount=${1}...    delay=${0.1}...    force=${True}Add Locator Handler Custom    id=overlay    [${handler_spec}]

The keyword can only handle click, fill, check and uncheck Playwright API calls. If there is a need for more complex interactions, it is recommended to create a custom js extension to handle the interactions.

Example:

async function customLocatorHandler(locator, pageLocator, clickLocator, page) {    console.log("Adding custom locator handler for: " + locator);    const pageLocator = page.locator(locator).first();    await page.addLocatorHandler(        pageLocator,        async () => {            console.log("Handling custom locator: " + clickLocator);            // More complex interactions can be added here            await page.locator(clickLocator).click();        }    );}exports.__esModule = true;exports.customLocatorHandler = customLocatorHandler;

Locator Handlers, line 108

Add Style Tag

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

Arguments

NameDefaultType
contentrequiredstr

Tags

PageContentSetter

Documentation

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

The tag is added to the currently active page and it is lost when the page is navigated to a new url.

Arguments Description
content Raw CSS content to be injected into the current page.

Example:

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

Comment >>

JavaScript Evaluation, line 158

Advance Clock

Advances the clock by a specified amount of time.

Arguments

NameDefaultType
timerequiredtimedelta
advance_type=fast_forwardCLockAdvanceType

Tags

ClockSetter

Documentation

Advances the clock by a specified amount of time.

Arguments Description
time The time to advance. Supports Robot Framework time format
advance_type The type of advance. Default is fast_forward.

run_for advances the clock by firing all the time-related callbacks.

fast_forward advances the clock by jumping forward in time. It fires due timers at most once.

Clock, line 95

Check Checkbox

Checks the checkbox or selects radio button found by selector.

Arguments

NameDefaultType
selectorrequiredstr
force=Falsebool

Tags

PageContentSetter

Documentation

Checks the checkbox or selects radio button found by selector.

Arguments Description
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 >>

Interaction, line 693

Clear Text

Clears the text field found by selector.

Arguments

NameDefaultType
selectorrequiredstr

Tags

PageContentSetter

Documentation

Clears the text field found by selector.

Arguments Description
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.

Comment >>

Interaction, line 119

Click

Simulates mouse click on the element found by selector.

Arguments

NameDefaultType
selectorrequiredstr
button=leftMouseButton

Tags

PageContentSetter

Documentation

Simulates mouse click on the element found by selector.

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

  • Find an element matching the selector. If there is none, wait until a matching element is attached to the DOM.
  • Wait for actionability checks on the matched element. 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.
  • Wait for initiated navigation to either succeed or fail.
Arguments Description
selector Selector element to click. See the Finding elements section for details about the selectors.
button Mouse button to click with. One of left, middle or right. Defaults to left.

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

See Click With Options if you need modifiers, a click count, a click position or want to skip the actionability checks.

Example:

Click    id=button_locationClick    id=button_location    leftClick    id=button_location    right

Comment >>

Interaction, line 321

Click With Options

Simulates mouse click on the element found by selector.

Arguments

NameDefaultType
selectorrequiredstr
button=leftMouseButton
*modifiersKeyboardModifier
clickCountnamed only=1int
delaynamed only=NoneUnion
forcenamed only=Falsebool
noWaitAfternamed only=Falsebool
position_xnamed only=NoneUnion
position_ynamed only=NoneUnion
trialnamed only=Falsebool

Tags

PageContentSetter

Documentation

Simulates mouse click on the element found by selector.

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

  • Find an element matching the selector. If there is none, wait until a matching element is attached to the DOM.
  • Wait for actionability checks on the matched element, unless the 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 the noWaitAfter option is set.
Arguments Description
selector Selector element to click. See the Finding elements section for details about the selectors.
button Mouse button to click with. One of left, middle or right. Defaults to left.
*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 Alt, Control, ControlOrMeta, Meta and Shift. 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.
clickCount How many times the button is clicked. Defaults to 1.
delay Time to wait between mouse-down and mouse-up. Defaults to no delay.
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. Both values must be given, otherwise the position is ignored. If not specified, clicks to some visible point of the element.
force Set to True to skip Playwright's Actionability checks (https://playwright.dev/docs/actionability). Defaults to False.
noWaitAfter Deprecated. This option will default to true in the future. 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.
trial When set, this method only performs the actionability checks and skips the action. Defaults to False. Useful to wait until the element is ready for the action without performing it.

Arguments clickCount, delay, position_x, position_y, force, noWaitAfter and trial are named-only arguments and must be specified using their names.

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

Example:

Click With Options    id=button_locationClick With Options    id=button_location    trial=TrueClick With Options    \#clickWithOptions    delay=100ms    clickCount=2Click With Options    id=clickWithModifiers    left     Alt    Meta    Shift    clickCount=1    force=TrueClick With Options    id=clickWithOptions    right    clickCount=2    force=True

Comment >>

Interaction, line 352

Close Browser

Closes the current browser.

Arguments

NameDefaultType
browser=CURRENTUnion

Tags

BrowserControlSetter

Documentation

Closes the current browser.

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.

Argument Description
browser Browser to close. CURRENT selects the active browser. ALL closes all browsers. When a browser id is provided, that browser is closed.

Example:

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

Comment >>

Browser, Context & Page, line 118

Close Browser Server

Close a playwright Browser Server identified by its websocket endpoint (wsEndpoint).

Arguments

NameDefaultType
wsEndpointrequiredstr

Tags

BrowserControlSetter

Documentation

Close a playwright Browser Server identified by its websocket endpoint (wsEndpoint).

The wsEndpoint string is returned by Launch Browser Server and is also used by Connect To Browser.

Arguments Description
wsEndpoint | Address of the browser server. Example: `ws://127.0.0.1:63784/ca69bf0e9471391e8183d9ac1e90e1ba`|

Browser, Context & Page, line 552

Close Context

Closes a Context.

Arguments

NameDefaultType
context=CURRENTUnion
browser=CURRENTUnion
save_tracenamed only=Truebool

Tags

BrowserControlSetter

Documentation

Closes a Context.

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.

Argument Description
context Context to close. CURRENT selects the active context. ALL selects all contexts. When a context id is provided, that context is closed.
browser Browser in which contexts are closed. CURRENT selects the active browser. ALL selects all browsers. When a browser id is provided, contexts of that browser are closed. The browsers themselves are not closed.
save_trace If set to False, the trace of this context is not saved, even if it was enabled by New Context. Defaults to True.

Example:

Close Context                          #  Closes the current context of the current browserClose Context    CURRENT    CURRENT    #  Closes the current context of the current browserClose Context    ALL        CURRENT    #  Closes all contexts of the current browserClose Context    ALL        ALL        #  Closes all contexts of all browsers

Comment >>

Browser, Context & Page, line 165

Close Page

Closes the page in context in browser.

Arguments

NameDefaultType
page=CURRENTUnion
context=CURRENTUnion
browser=CURRENTUnion
runBeforeUnload=Falsebool

Returns

list

Tags

BrowserControlSetter

Documentation

Closes the page in context in browser.

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.

runBeforeUnload defines where to run the before unload page handlers. Defaults to false.

Argument Description
page Page to close. CURRENT selects the active page. ALL selects all pages. When a page id is provided, that page is closed.
context Context in which pages are closed. CURRENT selects the active context. ALL selects all contexts. When a context id is provided, pages of that context are closed. The contexts themselves are not closed.
browser Browser in which pages are closed. CURRENT selects the active browser. ALL selects all browsers. When a browser id is provided, pages of that browser are closed. The browsers themselves are not closed.

If a page id is given, the context and browser arguments are ignored and the page is searched from all open browsers. Likewise, if a context id is given, the browser argument is ignored.

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 browserClose Page    CURRENT     CURRENT     CURRENT    # Closes current page, within the current context and browserClose Page    ALL         ALL         ALL        # Closes all pages, within all contexts and browsers

Comment >>

Browser, Context & Page, line 269

Connect To Browser

Connect to a Playwright browser server via playwright websocket or Chrome DevTools Protocol.

Arguments

NameDefaultType
wsEndpointrequiredstr
browser=chromiumSupportedBrowsers
use_cdp=Falsebool
timeoutnamed only=0:00:30timedelta

Tags

BrowserControlSetter

Documentation

Connect to a Playwright browser server via playwright websocket or Chrome DevTools Protocol.

See Launch Browser Server for more information about how to launch a playwright browser server.

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

Returns a stable identifier for the connected browser.

Argument Description
wsEndpoint Address to connect to. Either ws:// or http:// if cdp is used.
browser Opens the specified browser. Defaults to chromium.
use_cdp Connect to browser via Chrome DevTools Protocol. Defaults to False. Works only with Chromium based browsers.
timeout Maximum time in Robot Framework time format to wait for the connection to be established. Defaults to 30 seconds. The timeout can not be disabled; 0 also means 30 seconds.

To connect to a browser via Chrome DevTools Protocol, the browser must be started with this protocol enabled. This is typically done by starting a Chrome browser with the argument --remote-debugging-port=9222 or similar. When the browser is running with activated CDP, it is possible to connect to it either with websockets (ws://) or via HTTP (http://). The HTTP connection can be used when use_cdp is set to True. A typical address for a CDP connection is http://127.0.0.1:9222.

Comment >>

Browser, Context & Page, line 384

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. Links pointing to another scheme or host are ignored, as are download links.

Arguments

NameDefaultType
url=NoneUnion
page_crawl_keyword=take_screenshot
max_number_of_page_to_crawl=1000int
max_depth_to_crawl=50int

Tags

Crawling

Documentation

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. Links pointing to another scheme or host are ignored, as are download links.

Returns the list of crawled urls. The order of the returned urls is not guaranteed to be the order in which the pages were crawled.

Arguments Description
url is the page to start crawling from. If it is given, a New Page is opened with that url. If it is not given, crawling starts from the url of the current page.
page_crawl_keyword is the keyword that will be executed on every page. It is run without arguments. 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 when this number of pages has been crawled.
max_depth_to_crawl is the upper limit of consecutive links followed from the start page. The start page has depth 0 and links deeper than this limit are not followed.

Comment >>

Crawling, line 13

Create Credential

Creates a credential with the given parameters.

Arguments

NameDefaultType
rpIdrequiredstr
id_=NoneUnion
privateKey=NoneUnion
publicKey=NoneUnion
userHandle=NoneUnion

Tags

CredentialSetter

Documentation

Creates a credential with the given parameters.

Will always https://playwright.dev/docs/api/class-credentials#credentials-create and https://playwright.dev/docs/api/class-credentials#credentials-install the credential, even if the optional parameters are not provided. In this case Playwright will autogenerate the missing values.

The credential is created in the currently active context and it is used by all pages that are created from that context. There must be an open context, otherwise the keyword fails.

Arguments Description
rpId Relying party id (typically the site's effective domain).
id_ Base64url-encoded credential id. Auto-generated if omitted.
privateKey Base64url-encoded PKCS#8 (DER) private key. Auto-generated if omitted.
publicKey Base64url-encoded SPKI (DER) public key. Auto-generated if omitted.
userHandle Base64url-encoded user handle. Auto-generated if omitted.

Because privateKey and publicKey are sensitive information, it is recommended to wrap their values in the Secret type. The Secret type requires Robot Framework 7.4 or newer. If you are using Robot Framework 7.3 or older, the keyword supports resolving privateKey and publicKey from Robot Framework variables and environment variables in the following ways. The keyword resolves the value from a Robot Framework variable internally, when the variable is prefixed with $, without the curly braces. Example: $publicKey will resolve to the ${publicKey} Robot Framework variable.

If the privateKey or publicKey value is prefixed with %, the library will resolve the corresponding environment variable. Example: %PUBLICKEY will resolve to the %{PUBLICKEY} environment variable.

Plain values are not accepted. If the given privateKey or publicKey is not a Secret and does not resolve to another value, the keyword fails with an error stating that direct assignment of values or variables is not allowed.

Example:

New Context${credentials} =    Get Credentials   # This is a helper keyword that returns a dictionary with the required credential parameters.Create Credential...    rpId=${DOMAIN_NAME}...    id_=${credentials["id"]}...    privateKey=${credentials["privateKey"]}    # This should be a Secret type or a string starting with $ which resolves to a Robot Framework variable....    publicKey=${credentials["publicKey"]}    # This should be a Secret type or a string starting with $ which resolves to a Robot Framework variable....    userHandle=${credentials["userHandle"]}New Page    ${SUT_URL}Click    id=loginGet Text    id=status    ==    Success

Credentials, line 22

Delete All Cookies

Deletes all cookies from the currently active browser context.

Takes no arguments.

Tags

BrowserControlSetter

Documentation

Deletes all cookies from the currently active browser context.

Comment >>

Cookies, line 151

Delete Credential

Deletes the credential with the given id.

Arguments

NameDefaultType
id_requiredstr

Tags

CredentialSetter

Documentation

Deletes the credential with the given id.

Arguments Description
id_ Base64url-encoded credential id.

Deleting a credential which does not exist does not fail. There must be an open context, otherwise the keyword fails.

Example:

Delete Credential    id_=${CREDENTIAL_ID}

Credentials, line 200

Deselect Options

Deselects all options from select element found by selector.

Arguments

NameDefaultType
selectorrequiredstr

Tags

PageContentSetter

Documentation

Deselects all options from select element found by selector.

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

If you just want to select one or more specific options and currently more options are selected, use Select Options By keyword with the options to be selected in the end.

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

Comment >>

Interaction, line 810

Download

Download given url content.

Arguments

NameDefaultType
urlrequiredstr
saveAs=str
wait_for_finished=Truebool
download_timeout=NoneUnion

Tags

PageContent

Documentation

Download given url content.

Arguments Description
url URL to the file that shall be downloaded.
saveAs Path where the file shall be saved persistently. If empty, generated unique path (GUID) is used and file is deleted when the context is closed.
wait_for_finished If set to False keyword returns immediately after the download has started. Defaults to True.
download_timeout Timeout for the download itself if wait_for_finished is set to True. By default no timeout is set.

Keyword returns dictionary of type DownloadInfo.

Example:

{  "saveAs": "/tmp/robotframework-browser/downloads/2f1b3b7c-1b1b-4b1b-9b1b-1b1b1b1b1b1b",  "suggestedFilename": "downloaded_file.txt",  "state": "finished",  "downloadID": None,}

When wait_for_finished is False, the returned dictionary has an empty saveAs, the state is in_progress and downloadID contains the id of the download. The download can then be followed with the Get Download State keyword, which also saves the file to saveAs when the download is finished.

If the download should be started by an interaction with an element on the page, Promise To Wait For Download keyword may be a better choice.

The keyword New Browser has a downloadsPath setting which can be used to set the default download directory. If saveAs is set to a relative path, the file will be saved relative to the browser's downloadsPath setting or if that is not set, relative to the Playwright's working directory. If saveAs is set to an absolute path, the file will be saved to that absolute path independent of downloadsPath.

To enable downloads context's acceptDownloads needs to be true, otherwise the keyword fails. This keyword requires that there is currently an open page and that the page has been navigated to an url, downloading from about:blank fails. The download is done by a fetch call inside the page and therefore it uses the current page's local state (cookies, sessionstorage, localstorage) to avoid authentication problems. Because of that, a relative url is resolved against the current page url and the page's cross-origin restrictions apply.

Example:

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

Example 2:

${href}=          Get Property    text="Download File"    hrefDownload    ${href}    saveAs=${OUTPUT DIR}/downloads/downloaded_file.txtFile Should Exist    ${OUTPUT DIR}/downloads/downloaded_file.txt

Comment >>

JavaScript Evaluation, line 177

Drag And Drop

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

Arguments

NameDefaultType
selector_fromrequiredstr
selector_torequiredstr
steps=1int

Tags

PageContentSetter

Documentation

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

Arguments Description
selector_from Identifies the element whose center is the start-point.
selector_to Identifies the element whose center is the end-point.
steps Defines how many intermediate mouse move events are sent. Often it is necessary to send more than one intermediate event to get the desired result. Defaults to 1.

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' bounding box.

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

Example

Drag And Drop    "Circle"    "Goal"

Comment >>

Interaction, line 1107

Drag And Drop By Coordinates

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

Arguments

NameDefaultType
from_xrequiredfloat
from_yrequiredfloat
to_xrequiredfloat
to_yrequiredfloat
steps=1int

Tags

PageContentSetter

Documentation

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

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.

Arguments Description
from_x & from_y Identify the start-point on page.
to_x & to_y Identify the end-point.
steps Defines how many intermediate mouse move events are sent. Often it is necessary to send more than one intermediate event to get the desired result. Defaults to 1.

Example:

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

Comment >>

Interaction, line 1152

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

NameDefaultType
selector_fromrequiredstr
x=0.0float
y=0.0float
steps=1int

Tags

PageContentSetter

Documentation

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

This keyword can be handy to simulate swipe actions.

Arguments Description
selector_from Identifies the element whose center is the start-point.
x & y Identify the end-point, which is relative to the start-point.
steps Defines how many intermediate mouse move events are sent. Often it is necessary to send more than one intermediate event to get the desired result. Defaults to 1.

See the Finding elements section for details about the selectors.

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

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 pixels to the left

Comment >>

Interaction, line 1187

Emulate Media

Changes the CSS media type.

Arguments

NameDefaultType
colorScheme=NoneUnion
forcedColors=not_setUnion
media=NoneUnion
reducedMotion=NoneUnion

Returns

dict

Tags

PageContentSetter

Documentation

Changes the CSS media type.

It changes the CSS media type through the media argument, and/or the prefers-color-scheme media feature, using the colorScheme argument. This is useful to render the page in the correct format before using the Save Page As Pdf keyword.

Arguments Description
colorScheme Emulates the prefers-color-scheme media feature, supported values are light and dark. Passing null disables color scheme emulation. no-preference is deprecated.
forcedColors Emulates the forced-colors media feature, supported values are active and none. Passing null disables forced colors emulation.
media Changes the CSS media type of the page. The only allowed values are screen, print and null. Passing null disables CSS media emulation.
reducedMotion Emulates the prefers-reduced-motion media feature, supported values are reduce and no-preference. Passing null disables reduced motion emulation.

Arguments which are left to their default value are not sent to Playwright at all and therefore the corresponding emulation is left unchanged.

PDF, line 156

Evaluate JavaScript

Executes the given JavaScript in the browser page.

Arguments

NameDefaultType
selector=NoneUnion
*functionstr
argnamed only=NoneAny
all_elementsnamed only=Falsebool

Returns

Any

Tags

GetterPageContentSetter

Documentation

Executes the given JavaScript in the browser page.

The JavaScript is evaluated in the context of the page, not in the Node process of the library. Therefore browser globals like window and document are available, but Robot Framework variables and Python objects are not. Only arg and the resolved element(s) are passed into the page.

Arguments Description
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 element. 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. It is the second argument of the function when a selector is given, otherwise the first one. This argument must be JSON serializable. ElementHandles are not supported.
all_elements defines if only the single element found by selector is handed over to the function or if set to True all found elements are handed over as array.

The value returned by the JavaScript is transferred as JSON and must therefore be JSON serializable. DOM nodes and other non serializable objects can not be returned. If the JavaScript does not return anything, the keyword returns an empty string.

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 only if all_elements is False. See Finding elements for more details about strict mode.

Usage examples.

Comment >>

JavaScript Evaluation, line 34

Fill Secret

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

Arguments

NameDefaultType
selectorrequiredstr
secretrequiredUnion
force=Falsebool

Tags

PageContentSetter

Documentation

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

Arguments Description
selector Selector of the text field. See the Finding elements section for details about the selectors.
secret The secret string that should be filled into the text field. Supports Robot Framework 7.4 Secret type as normal variable (with curly braces). Also environment variable name with % prefix or a local variable with $ prefix that has the secret text value (without curly braces).
force Set to True to skip Playwright's Actionability checks.

This keyword does not log the secret in Robot Framework logs, but if Playwright debug logs are enabled, the secret will be visible as plain text in the Playwright debug logs, regardless of the Robot Framework log level or how secret is resolved.

This keyword supports Robot Framework 7.4 Secret variable type, which is the recommended way if you are using Robot Framework 7.4 or newer.

For older Robot Framework versions the keyword supports resolving secrets from environment variables and Robot Framework variables in the following ways. The keyword resolves the secret from a Robot Framework variable internally, when the secret variable is prefixed with $, without the curly braces. Example: $Password will resolve to the ${Password} Robot Framework variable.

If the secret variable is prefixed with %, the library will resolve the corresponding environment variable. Example: %ENV_PWD will resolve to the %{ENV_PWD} environment variable.

Using normal Robot Framework variables like ${password}, which are not Secret type variables, will not work!

Normal plain text will not work. If you want to use plain text, use the Fill Text keyword instead.

This keyword also works with a cryptographic cipher text that has been encrypted by CryptoLibrary. See CryptoLibrary for more details.

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

See Fill Text for other details.

Example:

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

Comment >>

Interaction, line 209

Fill Text

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

Arguments

NameDefaultType
selectorrequiredstr
txtrequiredstr
force=Falsebool

Tags

PageContentSetter

Documentation

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

This keyword 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 the selector is not an <input>, <textarea> or [contenteditable] element, this keyword fails. Note that you can pass an empty string as txt to clear the input field.

Arguments Description
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.

Example:

Fill Text    css=input#username_field    username

Comment >>

Interaction, line 89

Focus

Moves focus on to the element found by selector.

Arguments

NameDefaultType
selectorrequiredstr

Tags

PageContentSetter

Documentation

Moves focus on to the element found by selector.

Arguments Description
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 is no element matching the selector, the keyword waits until a matching element appears in the DOM. It fails if the element does not appear within the library timeout, which is 10 seconds by default and can be changed with Set Browser Timeout.

Comment >>

Interaction, line 567

Get Aria Snapshot

Returns the aria snapshot of the element found by selector. See `AriaSnapshotReturnType` for more details and examples.

Arguments

NameDefaultType
selectorrequiredstr
return_type=yamlAriaSnapshotReturnType
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion
modenamed only=defaultAriaSnapshotMode
depthnamed only=NoneUnion
boxesnamed only=Falsebool

Returns

Union

Tags

AssertionGetterPageContent

Documentation

Returns the aria snapshot of the element found by selector. See AriaSnapshotReturnType for more details and examples.

Arguments Description
selector Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.
return_type Defines the return type. Possible values are yaml (default), dict and parsed. If yaml is selected, the returned value is a string in YAML format. If dict is selected, the returned value is a dictionary. If parsed is selected, the returned value is a tree of node dictionaries.
assertion_operator See Assertions for further details. Defaults to None.
assertion_expected Expected value for the state
message overrides the default error message for assertion.
mode Defines the snapshot mode. Possible values are default (default) and ai. See AriaSnapshotMode for more details.
depth Limits the snapshot to the given number of tree levels. Must be a positive integer. Defaults to None, which does not limit the depth.
boxes If True, the bounding box of each element is appended to its line as [box=x,y,width,height]. Coordinates are relative to the viewport, in CSS pixels. Defaults to False.

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

With mode=ai the snapshot is optimized for AI consumption: it contains element references like [ref=e2] and the content of iframes inside the element. It also does not wait for a matching element, but fails immediately when no element matches, instead of failing with a timeout like the default mode does.

With return_type=dict the YAML returned by Playwright is loaded as is. The [ref=...] and [box=...] annotations are therefore part of the dictionary keys, not separate entries. Use return_type=parsed to get them as separate values of each node.

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

Example:

${aria} =    Get Aria Snapshot    id=main   # returns YAML stringLog Many    ${aria}${aria_dict} =    Get Aria Snapshot    id=main    dict   # returns dictionaryLog Many    ${aria_dict}

Comment >>

Getters & Assertions, line 67

Get Attribute

Returns the HTML attribute of the element found by selector.

Arguments

NameDefaultType
selectorrequiredstr
attributerequiredstr
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

Union

Tags

AssertionGetterPageContent

Documentation

Returns the HTML attribute of the element found by selector.

Arguments Description
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.
assertion_expected 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 an 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 check the presence or the absence 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: NoneGet Attribute   id=enabled_button    something    evaluate    value is not None    # PASS =>  returns: TrueGet Attribute   id=enabled_button    disabled     evaluate    value is None        # PASS =>  returns: True

Comment >>

Getters & Assertions, line 389

Get Attribute Names

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

Arguments

NameDefaultType
selectorrequiredstr
assertion_operator=NoneUnion
*assertion_expected
messagenamed only=NoneUnion

Returns

list

Tags

AssertionGetterPageContent

Documentation

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

Arguments Description
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.
*assertion_expected 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 names match the expected values. See Assertions for further details for the assertion arguments. By default assertion is not done.

Available assertions:

  • == , != and contains / *= can work with multiple values
  • validate and evaluate only accept one single expected value

Other operators are not allowed.

Example:

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 >>

Getters & Assertions, line 452

Get BoundingBox

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

Arguments

NameDefaultType
selectorrequiredstr
key=ALLBoundingBoxFields
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion
allow_hiddennamed only=Falsebool

Returns

Union

Tags

AssertionGetterPageContent

Documentation

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

Alternatively you can select a single attribute of the bounding box by setting the key argument.

If an element is hidden and has no bounding box, the keyword will fail. Depending on the method used to make an element invisible, an element might still have a bounding box which can be retrieved. To allow also hidden elements without a bounding box, set allow_hidden to True, which results in a return value of None in case of no bounding box.

Arguments Description
selector Selector from which the bounding box 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.
assertion_expected Expected value for the assertion
message overrides the default error message for assertion.
allow_hidden (named only) If True, hidden elements are not causing a failure and will return None. Otherwise a hidden element will fail. Defaults to False.

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                 # unfilteredLog                 ${bounding_box}                                 # {'x': 559.09375, 'y': 75.5, 'width': 188.796875, 'height': 18}${x}=               Get BoundingBox    id=element    x            # filteredLog                 X: ${x}                                         # X: 559.09375# Assertions:Get BoundingBox     id=element         width         >    180Get BoundingBox     id=element         ALL           validate    value['x'] > value['y']*2

Comment >>

Getters & Assertions, line 1263

Get Browser Catalog

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

Arguments

NameDefaultType
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

list

Tags

AssertionBrowserControlGetter

Documentation

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

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

Arguments Description
assertion_operator Optional assertion operator. See Assertions for more information.
assertion_expected Optional expected value. See Assertions for more information.
message Optional custom message to use on failure. See Assertions for more information.

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 >>

Browser, Context & Page, line 1066

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

NameDefaultType
browser=ALLSelectionType
assertion_operator=NoneUnion
*assertion_expectedUnion
messagenamed only=NoneUnion

Returns

list

Tags

AssertionBrowserControlGetter

Documentation

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

browser Defaults to ALL

  • ALL / ANY Returns all ids as a list.
  • ACTIVE / CURRENT Returns the id of the currently active browser as list.
Arguments Description
browser The browser to get the ids from. ALL for all open browsers or ACTIVE for the currently active browser.

The ACTIVE browser is a synonym for the CURRENT Browser.

Comment >>

Browser, Context & Page, line 1504

Get Checkbox State

Returns the state of the checkbox found by selector.

Arguments

NameDefaultType
selectorrequiredstr
assertion_operator=NoneUnion
assertion_expected=UncheckedUnion
message=NoneUnion

Returns

bool

Tags

AssertionGetterPageContent

Documentation

Returns the state of the checkbox found by selector.

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

Arguments Description
selector Selector which shall be examined. See the Finding elements section for details about the selectors.
assertion_operator == and != and equivalent are allowed on boolean values. Other operators are not accepted.
assertion_expected Boolean value of expected state. Strings are interpreted as booleans. All strings are ${True} except the following: FALSE, NO, OFF, 0, UNCHECKED, NONE, ${EMPTY} (case-insensitive). Defaults to Unchecked.
message overrides the default error message for assertion.
  • checked => True
  • unchecked => False

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

Example:

Get Checkbox State    [name=can_send_email]    ==    checked

Comment >>

Getters & Assertions, line 673

Get Classes

Returns all classes of an element as a list.

Arguments

NameDefaultType
selectorrequiredstr
assertion_operator=NoneUnion
*assertion_expected
messagenamed only=NoneUnion

Returns

list

Tags

AssertionGetterPageContent

Documentation

Returns all classes of an element as a list.

Arguments Description
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.
*assertion_expected Expected values 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 contains / *= can work with multiple values
  • validate and evaluate only accept one single expected value

Other operators are not allowed.

Example:

Get Classes    id=draggable    ==    react-draggable    box    # Element has exactly these class names.Get Classes    id=draggable    validate    "react-draggable-dragged" not in value    # Element does not contain react-draggable-dragged class.

Comment >>

Getters & Assertions, line 505

Get Client Size

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

Arguments

NameDefaultType
selector=NoneUnion
key=ALLSizeFields
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

Union

Tags

AssertionGetterPageContent

Documentation

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

Arguments Description
selector Optional selector from which the client size 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 client 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.
assertion_expected Expected value for the assertion
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 >>

Getters & Assertions, line 1458

Get Console Log

Returns the console log of the active page.

Arguments

NameDefaultType
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion
fullnamed only=Falsebool
lastnamed only=NoneUnion

Returns

list

Tags

AssertionBrowserControlGetter

Documentation

Returns the console log of the active page.

If assertions are used and fail, this keyword will fail immediately without retrying.

Arguments Description
assertion_operator Optional assertion operator. See Assertions for more information.
assertion_expected Optional expected value. See Assertions for more information.
message Optional custom message to use on failure. See Assertions for more information.
full If true, returns the full console log. If false, returns only new entries that were added since last time.
last If set, returns only the last n entries. Can be an integer for the number of entries or a time period in Robot Framework time format.

The returned data is a list of log messages.

A log message is a dictionary with the following structure:

[{  "type": str,  "text": str,  "location": {    "url": str,    "lineNumber": int,    "columnNumber": int  },  "time": str}]

Example:

[{  'type': 'log',  'text': 'Stuff loaded...',  'location': {    'url': 'https://example.com/js/chunk-769742de.6a462276.js',    'lineNumber': 60,    'columnNumber': 63771  },  'time': '2023-02-05T17:42:52.064Z'}]

Keys:

Key Description
type One of the following values: log, debug, info, error, warning, dir, dirxml, table, trace, clear, startGroup, startGroupCollapsed, endGroup, assert, profile, profileEnd, count, timeEnd
text The text of the console message.
location.url The URL of the resource that generated this message.
location.lineNumber The line number in the resource that generated this message (0-based).
location.columnNumber The column number in the resource that generated this message (0-based).
time The timestamp of the log message as ISO 8601 string.

Comment >>

Browser, Context & Page, line 1168

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

NameDefaultType
context=ALLSelectionType
browser=ALLUnion
assertion_operator=NoneUnion
*assertion_expectedUnion
messagenamed only=NoneUnion

Returns

list

Tags

AssertionBrowserControlGetter

Documentation

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

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

Arguments Description
context The context to get the ids from. ALL will return all ids from selected browser(s), ACTIVE for the one active context of each selected browser.
browser The browser id or selection to get the context ids from. ALL Context ids from all open browsers shall be fetched. ACTIVE Only context ids from the active browser shall be fetched. If a browser id is given and no browser with that id is open, the keyword fails.

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

Comment >>

Browser, Context & Page, line 1536

Get Cookies

Returns cookies from the currently active browser context.

Arguments

NameDefaultType
return_type=dictionaryCookieType

Returns

Union

Tags

GetterPageContent

Documentation

Returns cookies from the currently active browser context.

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

If return_type is string or str, then the keyword returns the cookies as a string in format: name1=value1; name2=value2; name3=value3. The return value contains only name and value keys of the cookies. If no cookies are found, an empty list is returned.

Comment >>

Cookies, line 28

Get Credential

Returns the credential matching the given id and/or rpId.

Arguments

NameDefaultType
id_=NoneUnion
rpId=NoneUnion

Tags

CredentialGetter

Documentation

Returns the credential matching the given id and/or rpId.

At least one of id_ and rpId must be given, otherwise the keyword fails. If both are given, the credential must match both of them. When more than one credential matches, the first match is returned. When no credential matches, the keyword fails.

Arguments Description
id_ Base64url-encoded credential id.
rpId Relying party id (typically the site's effective domain).

The returned credential is a dictionary with the following keys:

Key Description
id Base64url-encoded credential id.
rpId Relying party id (typically the site's effective domain).
userHandle Base64url-encoded user handle.
privateKey Base64url-encoded PKCS#8 (DER) private key as a Secret.
publicKey Base64url-encoded SPKI (DER) public key as a Secret.

The privateKey and publicKey are wrapped in the Secret type, so that their values are not shown in the Robot Framework log. The values themselves are available in the value attribute. Note that the node side of the library might write the whole credential, including the private key, as plain text to the playwright-log.txt file. See PlaywrightLogTypes for how to control that file.

See Install Credential for more information about how to use this keyword.

Example:

${credential} =    Get Credential    id_=${CREDENTIAL_ID}Should Be Equal    ${credential["id"]}    ${CREDENTIAL_ID}Should Be Equal    ${credential["rpId"]}    ${DOMAIN_NAME}Should Be Equal    ${credential["userHandle"]}    userhandleCreatedByTheAppShould Be Equal    ${credential["privateKey"].value}    privateKeyCreatedByTheAppShould Be Equal    ${credential["publicKey"].value}    publicKeyCreatedByTheApp

Credentials, line 139

Get Device

Returns a single device descriptor whose name matches name exactly.

Arguments

NameDefaultType
namerequiredstr

Returns

dict

Tags

BrowserControlGetter

Documentation

Returns a single device descriptor whose name matches name exactly.

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

The keyword fails if there is no device with that name. The matching is case sensitive.

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

Use the returned descriptor by passing it to New Context. After creating a context with a device descriptor, make sure that your active page is in that context before using it. Usage:

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

Comment >>

Devices, line 42

Get Devices

Returns a dictionary of all Playwright device descriptors.

Takes no arguments.

Returns

dict

Tags

BrowserControlGetter

Documentation

Returns a dictionary of all Playwright device descriptors.

The keys are the device names and the values are the device descriptors themselves.

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

Comment >>

Devices, line 24

Get Download State

Gets the state of a download.

Arguments

NameDefaultType
downloadrequiredUnion
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Tags

AssertionGetterPageContent

Documentation

Gets the state of a download.

Returns a dictionary of type DownloadInfo with the following keys:

{  saveAs: str  suggestedFilename: str  state: str  downloadID: Optional[str]}
Arguments Description
download DownloadInfo dictionary returned from Promise To Wait For Download or download id as string.
assertion_operator See Assertions for further details. Defaults to None.
assertion_expected Expected state of the download. Be aware that the returned value is a dictionary
message overrides the default error message for assertion.

Comment >>

Getters & Assertions, line 1591

Get Element

Returns a selector string that points to the element found by selector.

Arguments

NameDefaultType
selectorrequiredstr

Returns

str

Tags

GetterPageContent

Documentation

Returns a selector string that points to the element found by selector.

The returned string is the selector Playwright resolved for the element. It is an ordinary selector, so it can be used as the first clause of another selector, chained with >>. Because it is a selector and not a captured DOM node, it is resolved again from the page on every use.

Arguments Description
selector Selector from which the element 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.

Example:

${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 >>

Getters & Assertions, line 961

Get Element By

Allows locating elements by their features.

Arguments

NameDefaultType
selection_strategyrequiredSelectionStrategy
textrequiredUnion
exact=Falsebool
all_elements=Falsebool

Returns

str

Tags

GetterPageContent

Documentation

Allows locating elements by their features.

Selection strategies can be several Playwright strategies like AltText or Label. See Playwright Locators for more information.

Arguments Description
selection_strategy SelectionStrategy to be used. Refers to Playwrights page.getBy*** functions. See https://playwright.dev/docs/locators
text Text to locate the element for.
exact Whether to find an exact match: case-sensitive and whole-string. Defaults to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace. This has no effect if RegExp is used or if TestID is used as strategy.
all_elements If True, returns all matched elements as a list.

This keywords implements the following Playwright functions:

page.getByRole is supported by Get Element By Role keyword.

If an element shall be fetched from an iframe, a selector prefix must be set using Set Selector Prefix keyword including >>> as ending.

Comment >>

Getters & Assertions, line 1128

Get Element By Role

Returns a selector string for the element matched by role, or a list of selector strings if all_elements is set to True.

Arguments

NameDefaultType
rolerequiredElementRole
all_elementsnamed only=Falsebool
checkednamed only=NoneUnion
disablednamed only=NoneUnion
exactnamed only=NoneUnion
expandednamed only=NoneUnion
include_hiddennamed only=NoneUnion
levelnamed only=NoneUnion
namenamed only=NoneUnion
pressednamed only=NoneUnion
selectednamed only=NoneUnion

Returns

str

Tags

GetterPageContent

Documentation

Returns a selector string for the element matched by role, or a list of selector strings if all_elements is set to True.

The returned value is used like the one from Get Element: as the first clause of another selector, chained with >>.

Allows locating elements by their ARIA role, ARIA attributes and accessible name.

Consider the following DOM structure.

<h3>Sign up</h3><label>  <input type="checkbox" /> Subscribe</label><br/><button>Submit</button>

You can locate each element by its implicit role:

${heading}    Get Element By Role    heading    name=Sign up${checkbox}   Get Element By Role    checkbox    name=Subscribe${button}     Get Element By Role    button    name=/submit/i
Arguments Description
all_elements If True, returns all matched elements as a list.
role Role from which shall be retrieved.
checked An attribute that is usually set by aria-checked or native <input type=checkbox> controls.
disabled An attribute that is usually set by aria-disabled or disabled.
exact Whether name is matched exactly: case-sensitive and whole-string. Defaults to false. Ignored when name is a regular expression. Note that exact match still trims whitespace.
expanded An attribute that is usually set by aria-expanded.
include_hidden Option that controls whether hidden elements are matched. By default, only non-hidden elements, as defined by ARIA, are matched by role selector.
level A number attribute that is usually present for roles heading, list item, row, treeitem, with default values for <h1>-<h6> elements.
name Option to match the accessible name. By default, matching is case-insensitive and searches for a substring, use exact to control this behavior.
pressed An attribute that is usually set by aria-pressed.
selected An attribute that is usually set by aria-selected.

If an element shall be fetched from an iframe, a selector prefix must be set using Set Selector Prefix keyword including >>> as ending.

Comment >>

Getters & Assertions, line 1030

Get Element Count

Returns the count of elements found with selector.

Arguments

NameDefaultType
selectorrequiredstr
assertion_operator=NoneUnion
assertion_expected=0Union
message=NoneUnion

Returns

int

Tags

AssertionGetterPageContent

Documentation

Returns the count of elements found with selector.

Arguments Description
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.
assertion_expected Expected value for the assertion
message overrides the default error message for assertion.

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

Example:

Get Element Count    label    >    1

Comment >>

Getters & Assertions, line 723

Get Element States

Get the active states from the element found by selector.

Arguments

NameDefaultType
selectorrequiredstr
assertion_operator=NoneUnion
*assertion_expectedUnion
messagenamed only=NoneUnion
return_namesnamed only=True

Returns

Union

Tags

AssertionGetterPageContent

Documentation

Get the active states from the element found by selector.

This Keyword returns a list of states that are valid for the selected element.

Arguments Description
selector Selector of the corresponding object. See the Finding elements section for details about the selectors.
assertion_operator See Assertions for further details. Defaults to None.
*assertion_expected Expected states
message overrides the default error message for assertion.
return_names If set to False the keyword does return an IntFlag object (ElementState) instead of a list. ElementState may contain multiple states at the same time. Defaults to True.

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 contains the states as ElementState.

Example:

Get Element States    h1    validate    value & visible   # Fails in case of an invisible elementGet 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      *=    checkedGet Element States    id=checked_elem      not contains    checkedGet Element States    id=invisible_elem    contains    hidden    attachedGet 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. Options of select elements have also either selected or deselected.

If an element is not attached to the DOM, so that 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 >>

Getters & Assertions, line 1508

Get Elements

Returns a list of selector strings, one for each element matched by selector.

Arguments

NameDefaultType
selectorrequiredstr

Returns

list

Tags

GetterPageContent

Documentation

Returns a list of selector strings, one for each element matched by selector.

Each string can be used as the first clause of another selector, chained with >>, exactly like the value returned by Get Element.

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

Keyword does not use strict mode and returns an empty list if the selector does not match any element.

Example:

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

Comment >>

Getters & Assertions, line 991

Get Page Errors

Returns the page errors of the active page.

Arguments

NameDefaultType
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion
fullnamed only=Falsebool
lastnamed only=NoneUnion

Returns

list

Tags

AssertionBrowserControlGetter

Documentation

Returns the page errors of the active page.

If assertions are used and fail, this keyword will fail immediately without retrying.

Arguments Description
assertion_operator Optional assertion operator. See Assertions for more information.
assertion_expected Optional expected value. See Assertions for more information.
message Optional custom message to use on failure. See Assertions for more information.
full If true, returns all page errors. If false, returns only new errors that were added since last time.
last If set, returns only the last n entries. Can be an integer for the number of entries or a time period in Robot Framework time format.

The returned data is a list of error messages.

An error message is a dictionary with the following structure:

{  "name": str,  "message": str,  "stack": str,  "time": str}

Example:

[{  'name': 'ReferenceError',  'message': 'YT is not defined',  'stack': 'ReferenceError: YT is not defined\n    at HTMLIFrameElement.onload (https://example.com/:20:2245)',  'time': '2023-02-05T20:08:48.912Z'}]

Keys:

Key Description
name The name/type of the error.
message The human readable error message.
stack The stack trace of the error, if given.
time The timestamp of the error as ISO 8601 string.

Comment >>

Browser, Context & Page, line 1240

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

NameDefaultType
page=ALLSelectionType
context=ALLUnion
browser=ALLUnion
assertion_operator=NoneUnion
*assertion_expectedUnion
messagenamed only=NoneUnion

Returns

list

Tags

AssertionBrowserControlGetter

Documentation

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.

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

Arguments Description
page The page to get the ids from. ALL Returns all page ids as a list. ACTIVE Returns the id of the active page as a list.
context The context id or selection to get the page ids from. ALL Page ids from all contexts shall be fetched. ACTIVE Only page ids from the active context shall be fetched.
browser The browser id or selection to get the page ids from. ALL Page ids from all open browsers shall be fetched. ACTIVE Only page ids from the active browser shall be fetched.

Example:

Test Case    New Page    https://www.imbus.de    New Page    https://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}

Example to count open pages of a specific context:

Test Case   New Browser    firefox   ${context}=    New Context   New Page    https://www.imbus.de   New Page    https://www.op.fi   New Context   New Page    https://www.robocon.io   ${page_count}=    Get Page IDs    ALL    ${context}    ALL    then    len(value)   Should Be Equal As Integers    ${page_count}    2

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

Comment >>

Browser, Context & Page, line 1620

Get Page Source

Gets the page's HTML source as a string.

Arguments

NameDefaultType
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

Union

Tags

AssertionGetterPageContent

Documentation

Gets the page's HTML source as a string.

Arguments Description
assertion_operator See Assertions for further details. Defaults to None.
assertion_expected 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.

If the HTML of a single element is needed, use Get Property instead. Example:

${html1} =    Get Property    ${selector}    innerHTML${html2} =    Get Property    ${selector}    outerHTML

Comment >>

Getters & Assertions, line 178

Get Property

Returns the property of the element found by selector.

Arguments

NameDefaultType
selectorrequiredstr
propertyrequiredstr
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

Any

Tags

AssertionGetterPageContent

Documentation

Returns the property of the element found by selector.

Arguments Description
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.
assertion_expected 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 the property is not found, value is None and the keyword does not fail. If no assertion_operator is set and the property is not found, the keyword fails. See Get Attribute for examples.

Example:

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

Comment >>

Getters & Assertions, line 329

Get Scroll Position

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

Arguments

NameDefaultType
selector=NoneUnion
key=ALLAreaFields
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

Union

Tags

AssertionGetterPageContent

Documentation

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

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

Arguments Description
selector Optional selector from which the scroll position shall be retrieved. If no selector is given the scroll position 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.
assertion_expected Expected value for the assertion
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 >>

Getters & Assertions, line 1402

Get Scroll Size

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

Arguments

NameDefaultType
selector=NoneUnion
key=ALLSizeFields
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

Union

Tags

AssertionGetterPageContent

Documentation

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

Arguments Description
selector Optional selector from which the scroll size 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.
assertion_expected Expected value for the assertion
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 heightLog                Height: ${height}                                  # Height: 58425${scroll_size}=    Get Scroll Size    id=keyword-shortcuts-container  # unfiltered elementLog                ${scroll_size}                                     # {'width': 253, 'height': 3036}

Comment >>

Getters & Assertions, line 1346

Get Select Options

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

Arguments

NameDefaultType
selectorrequiredstr
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

list

Tags

AssertionGetterPageContent

Documentation

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

Each returned dictionary has the keys "index", "value", "label" and "selected".

Arguments Description
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.
assertion_expected 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.

Example:

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 >>

Getters & Assertions, line 552

Get Selected Options

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

Arguments

NameDefaultType
selectorrequiredstr
option_attribute=labelSelectAttribute
assertion_operator=NoneUnion
*assertion_expected
messagenamed only=NoneUnion

Returns

list

Tags

AssertionGetterPageContent

Documentation

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

Arguments Description
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.
assertion_operator See Assertions for further details. Defaults to None.
*assertion_expected 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.

  • == , != and contains / *= can work with multiple values
  • validate and evaluate only accept one single expected value

Other operators are not allowed.

Example:

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

Comment >>

Getters & Assertions, line 611

Get Style

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

Arguments

NameDefaultType
selectorrequiredstr
key=ALLUnion
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion
pseudo_element=NoneUnion

Returns

Union

Tags

AssertionGetterPageContent

Documentation

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

Arguments Description
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 as dictionary by default. All css settings can be used as keys even if they are not all returned in the dictionary.
assertion_operator See Assertions for further details. Defaults to None.
assertion_expected Expected value for the assertion
message overrides the default error message for assertion.
pseudo_element Pseudo element to match. Defaults to None.

A pseudo element is a CSS functionality to add styles, for example ::before or ::after.

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.

When key is ALL, a dictionary is returned and only the sequence assertion operators ==, !=, contains / *=, validate and evaluate / then are allowed. Assertion formatters are not applied in that case.

Comment >>

Getters & Assertions, line 1190

Get Table Cell Element

Returns a selector string for the cell at the same column and row index as the selected elements.

Arguments

NameDefaultType
tablerequiredstr
columnrequiredstr
rowrequiredstr

Returns

str

Tags

GetterPageContent

Documentation

Returns a selector string for the cell at the same column and row index as the selected elements.

The returned value is used like the one from Get Element.

Arguments Description
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 descendants 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 the table selector like this: f"{table} >> {column}" and f"{table} >> {row}".

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

Example:

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

Comment >>

Getters & Assertions, line 817

Get Table Cell Index

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

Arguments

NameDefaultType
selectorrequiredstr
assertion_operator=NoneUnion
assertion_expected=0Union
message=NoneUnion

Returns

int

Tags

AssertionGetterPageContent

Documentation

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

Arguments Description
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.
assertion_expected Expected value for the assertion
message overrides the default error message for assertion.

Example:

${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 >>

Getters & Assertions, line 875

Get Table Row Index

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

Arguments

NameDefaultType
selectorrequiredstr
assertion_operator=NoneUnion
assertion_expected=0Union
message=NoneUnion

Returns

int

Tags

AssertionGetterPageContent

Documentation

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

Arguments Description
selector can select any <tr>, <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.
assertion_expected Expected value for the assertion
message overrides the default error message for assertion.

Example:

${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 >>

Getters & Assertions, line 918

Get Text

Returns text attribute of the element found by selector.

Arguments

NameDefaultType
selectorrequiredstr
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion
text_typenamed only=NoneUnion

Returns

Union

Tags

AssertionGetterPageContent

Documentation

Returns text attribute of the element found by selector.

Keyword can also return the value property text of input or textarea elements. See the Finding elements section for details about the selectors.

Arguments Description
selector Selector from which the text is to be retrieved. See the Finding elements section for details about the selectors.
assertion_operator See Assertions for further details. Defaults to None.
assertion_expected Expected value for the state
message overrides the default error message for assertion.
text_type How text is returned. Possible values are allInnerTexts, allTextContents, innerText, inputValue, and innerHTML. Defaults to None, which returns the value of input and textarea elements and the inner text of all other elements.

Keyword uses strict mode, see Finding elements for more details about strict mode. The text_type argument determines how text is returned. The allInnerTexts and allTextContents will return a list of strings, while other types return a single string.

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

Example:

${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.${text} =    Get Text    id=important    text_type=innerHTML         # Returns element inner HTML.${text} =    Get Text    id=important    text_type=allInnerTexts     # Returns element inner text as list of strings.

Comment >>

Getters & Assertions, line 256

Get Title

Returns the title of the current page.

Arguments

NameDefaultType
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

Union

Tags

AssertionGetterPageContent

Documentation

Returns the title of the current page.

Arguments Description
assertion_operator See Assertions for further details. Defaults to None.
assertion_expected 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.

Comment >>

Getters & Assertions, line 220

Get Url

Returns the current URL.

Arguments

NameDefaultType
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

Union

Tags

AssertionGetterPageContent

Documentation

Returns the current URL.

Arguments Description
assertion_operator See Assertions for further details. Defaults to None.
assertion_expected 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.

Comment >>

Getters & Assertions, line 148

Get Viewport Size

Returns the current viewport dimensions.

Arguments

NameDefaultType
key=ALLSizeFields
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

Union

Tags

AssertionBrowserControlGetter

Documentation

Returns the current viewport dimensions.

Arguments Description
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.
assertion_expected Expected value for the assertion
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.

If the page does not have a viewport size, for example because the context was created without one, None is returned and no assertion is done.

Example:

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

Comment >>

Getters & Assertions, line 763

Go To

Navigates to the given url.

Arguments

NameDefaultType
urlrequiredstr
timeout=NoneUnion
wait_until=loadPageLoadStates

Tags

BrowserControlSetter

Documentation

Navigates to the given url.

Arguments Description
url URL to be navigated to.
timeout Time to wait for the page to load. If not defined, the library default timeout is used.
wait_until When to consider the operation succeeded, defaults to load. The event can be either: domcontentloaded - consider the operation to be finished when the DOMContentLoaded event is fired. load - consider the operation to be finished when the load event is fired. networkidle - consider the operation to be finished when there are no network connections for at least 500 ms. commit - consider the operation to be finished when the network response is received and the document started loading.

Returns the HTTP status code of the navigation request as an integer, or 0 if no response was received.

Comment >>

Browser Control, line 72

Grant Permissions

Grants permissions to the current context.

Arguments

NameDefaultType
*permissionsPermission
originnamed only=NoneUnion

Tags

BrowserControlSetter

Documentation

Grants permissions to the current context.

Arguments Description
permissions Permissions to grant, given as separate arguments. See Permission for the available values, for example geolocation, notifications, camera or microphone.
origin The origin to grant the permissions to, e.g. "https://example.com". If not given, the permissions are granted for all origins.

Example:

New ContextGrant Permissions    geolocation

Comment >>

Browser Control, line 619

Handle Future Dialogs

Handle next dialog on page with action.

Arguments

NameDefaultType
actionrequiredDialogAction
prompt_input=str

Tags

PageContent

Documentation

Handle next dialog on page with action.

The dialog can be an alert, beforeunload, confirm or prompt dialog. This keyword must be called before the action, for example a click, which triggers the dialog.

The handler is registered on the current page and stays in effect for all following dialogs on that page. Calling this keyword again on the same page replaces the handler, so the latest call decides how dialogs are handled.

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

The handler runs when the dialog appears, not while this keyword executes, so a failure to accept or dismiss the dialog can not be raised as a keyword failure. Such a failure is reported in the playwright-log.txt file only, which is linked into the Robot Framework log when a keyword fails.

Arguments Description
action How to handle the alert. Can be accept or dismiss.
prompt_input The value to enter into the prompt. Only valid if the action argument equals accept. Defaults to an empty string.

Example:

Handle Future Dialogs    action=acceptClick                    \#alerts

Comment >>

Interaction, line 874

Highlight Elements

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

Arguments

NameDefaultType
selectorrequiredstr
duration=0:00:05timedelta
width=2pxstr
style=dottedstr
color=bluestr
modenamed only=borderHighlightMode

Tags

PageContentSetter

Documentation

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

Returns the number of highlighted elements. Keyword does not fail, if the selector matched zero elements in the page. Keyword does not scroll elements to viewport and highlighted element might be outside the viewport. Use Scroll To Element keyword to scroll element in viewport.

Arguments Description
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. If set to 0 seconds, the highlighting is not deleted.
width Sets the width of the highlight 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
mode Sets the mode of the highlight. Valid modes are: border (classic mode), playwright (Playwright's native one) and both. Defaults to border. If playwright is used, width, style and color are ignored and only one highlighting can happen at the same time.

Keyword does not fail if selector resolves to multiple elements.

Highlights which are created with duration=0 stay in the page until they are removed. Calling this keyword with an empty selector, for example Highlight Elements ${EMPTY}, removes all such highlights that were made with Playwright's native highlighting, in other words with mode=playwright or mode=both. Highlights drawn in border mode can not be removed that way.

Example:

Highlight Elements    input#login_button    duration=200ms${count} =    Highlight Elements    input#login_button    duration=200ms    width=4px    style=solid    color=\#FF00FFShould Be Equal    ${count}    ${5}

Comment >>

JavaScript Evaluation, line 97

Hover

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

Arguments

NameDefaultType
selectorrequiredstr
position_x=NoneUnion
position_y=NoneUnion
force=Falsebool
*modifiersKeyboardModifier

Tags

PageContentSetter

Documentation

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

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

  • Find an element 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 the 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.
Arguments Description
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. Both values must be given, otherwise the position is ignored.
force Set to True to skip Playwright's Actionability checks. Defaults to False.
*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. Valid modifier keys are Alt, Control, ControlOrMeta, Meta and Shift.

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

Example:

Hover    h1Hover    h1    10   20    Alt

Comment >>

Interaction, line 516

Http

Performs an HTTP request in the current browser context

Arguments

NameDefaultType
urlrequiredstr
method=GETRequestMethod
body=NoneUnion
headers=NoneUnion

Returns

Any

Tags

HTTP

Documentation

Performs an HTTP request in the current browser context

The request is sent with the browser's fetch from the currently active page, so a relative url is resolved against the URL of that page.

Arguments Description
url The request url, e.g. /api/foo.
method The HTTP method for the request. Defaults to GET.
body The request body. It is ignored for GET requests, because GET requests cannot have a body. If the body can be parsed as JSON, the Content-Type header for the request is automatically set to application/json, unless headers already contains that header. Defaults to None.
headers A dictionary of additional request headers. Defaults to None.

The response is a Robot Framework dictionary with the following attributes:

  • status <int> The status code of the response.
  • statusText <str> Status text corresponding to status, e.g. OK or INTERNAL SERVER ERROR. This may not be available for all browsers.
  • body <dict> | <str> The response body. If the body can be parsed as a JSON object, 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 successful, i.e. the status is in the range 200-299.
  • url <str> The final URL of the response, after possible redirects.
  • redirected <bool> Whether the response is the result of a redirect.
  • type <str> The type of the response, e.g. basic or cors.

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

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

Comment >>

Network, line 59

Install Credential

Installs the virtual WebAuthn authenticator into the context.

Takes no arguments.

Tags

CredentialSetter

Documentation

Installs the virtual WebAuthn authenticator into the context.

Overrides navigator.credentials.create() and navigator.credentials.get() in all current and future pages of the context. Call this before the page first touches navigator.credentials.

Until the authenticator is installed, no interception is in place and the page sees the platform's native (or absent) WebAuthn behavior. Create Credential installs the authenticator as well, so this keyword is mainly needed when the credentials are created by the application itself. There must be an open context, otherwise the keyword fails.

Example:

New ContextInstall CredentialNew Page    ${SUT_URL}# Do something on the page that causes the page to call navigator.credentials.create()${credential_id} =    Get Credential Id   # This is a user keyword that returns the credential id from somewhere. Talk to your application team to find out how to get the credential id.${credential} =    Get Credential    id_=${credential_id}    # This will return the credential that was created by the application and installed into the context.New ContextCreate Credential...    rpId=${DOMAIN_NAME}...    id_=${credential["id"]}...    privateKey=${credential["privateKey"]}...    publicKey=${credential["publicKey"]}...    userHandle=${credential["userHandle"]}New Page    ${SUT_URL}# User should be able to interact with the page using the installed credential.

Credentials, line 104

Keyboard Input

Input text into page with virtual keyboard.

Arguments

NameDefaultType
actionrequiredKeyboardInputAction
inputrequiredstr
delay=0:00:00Union

Tags

PageContentSetter

Documentation

Input text into page with virtual keyboard.

Arguments Description
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 input string to be typed. No special keys possible.
delay Time to wait between key presses in Robot Framework's time format. Defaults to 0 ms.

Attention: Argument type int for 'delay' in milliseconds has been changed to timedelta in Browser 14.0.0. Use Robot Framework time format with units instead.

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

Example:

Keyboard Input    insertText    0123456789

Comment >>

Interaction, line 1360

Keyboard Key

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

Arguments

NameDefaultType
actionrequiredKeyAction
keyrequiredstr
delaynamed only=0:00:00timedelta

Tags

PageContentSetter

Documentation

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

Arguments Description
action Determines whether the key should be released (up), held down (down) or pressed once (press). down and up are useful for combinations, i.e. with Shift.
key The key to be pressed. Examples 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.
delay Time the key is held down between keydown and keyup, in Robot Framework's time format. Only valid with action press, other actions raise an error. Defaults to 0 s. Example: 50 ms

Useful keys for down and up for example are: Shift, Control, Alt, Meta, ShiftLeft

Example execution:

Keyboard Key    press    SKeyboard Key    press    S        delay=500 msKeyboard Key    down     ShiftKeyboard Key    press    ArrowLeftKeyboard Key    press    DeleteKeyboard Key    up       Shift

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

Comment >>

Interaction, line 1321

Launch Browser Server

Launches a new playwright Browser server with specified options.

Arguments

NameDefaultType
browser=chromiumSupportedBrowsers
headless=Truebool
argsnamed only=NoneUnion
channelnamed only=NoneUnion
chromiumSandboxnamed only=Falsebool
devtoolsnamed only=Falsebool
downloadsPathnamed only=NoneUnion
envnamed only=NoneUnion
executablePathnamed only=NoneUnion
firefoxUserPrefsnamed only=NoneUnion
handleSIGHUPnamed only=Truebool
handleSIGINTnamed only=Truebool
handleSIGTERMnamed only=Truebool
ignoreDefaultArgsnamed only=NoneUnion
portnamed only=NoneUnion
proxynamed only=NoneUnion
reuse_existingnamed only=Truebool
slowMonamed only=0:00:00timedelta
timeoutnamed only=0:00:30timedelta
wsPathnamed only=NoneUnion

Returns

str

Tags

BrowserControlSetter

Documentation

Launches a new playwright Browser server with specified options.

Returns a websocket endpoint (wsEndpoint) string that can be used to connect to the server.

Arguments Description
port Port to use for the browser server. Defaults to 0, which results in a random free port being assigned.
wsPath Path at which to serve the browser server. For security, this defaults to an unguessable string.

Check New Browser for the other argument docs.

The launched browser server can be used to connect to it with Connect To Browser keyword. This keyword can also be used from command line with rfbrowser launch-browser-server command.

See Playwright documentation for more information.

Comment >>

Browser, Context & Page, line 499

LocalStorage Clear

Remove all saved data from the local storage.

Arguments

NameDefaultType
frame_selector=NoneUnion

Tags

PageContentSetter

Documentation

Remove all saved data from the local storage.

Arguments Description
frame_selector If this selector points to an element inside an iframe, the LocalStorage of that frame is used. Example: iframe[name="test"] >>> body

Example:

LocalStorage Set Item    Foo    barLocalStorage Clear${item} =    LocalStorage Get Item    FooShould Be Equal    ${item}    ${None}

Comment >>

Web App State, line 129

LocalStorage Get Item

Get saved data from the local storage.

Arguments

NameDefaultType
keyrequiredstr
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion
frame_selector=NoneUnion

Returns

Any

Tags

AssertionGetterPageContent

Documentation

Get saved data from the local storage.

Arguments Description
key Named key of the item in the storage.
assertion_operator Assertion operator to use. See Assertions for more information.
assertion_expected Expected value to compare with.
message Custom error message to use.
frame_selector If this selector points to an element inside an iframe, the LocalStorage of that frame is used. Example: iframe[name="test"] >>> body

See Assertions for further details about the assertion arguments. They default to None.

If the key does not exist in the storage, ${None} is returned.

Example:

LocalStorage Get Item    Key    ==    Value    My error${value} =    LocalStorage Get Item    Key

Comment >>

Web App State, line 42

LocalStorage Remove Item

Remove saved data with key from the local storage.

Arguments

NameDefaultType
keyrequiredstr
frame_selector=NoneUnion

Tags

PageContentSetter

Documentation

Remove saved data with key from the local storage.

Arguments Description
key The name of the item which shall be deleted.
frame_selector If this selector points to an element inside an iframe, the LocalStorage of that frame is used. Example: iframe[name="test"] >>> body

Example:

LocalStorage Set Item       Foo    barLocalStorage Remove Item    Foo${item} =    LocalStorage Get Item    FooShould Be Equal    ${item}    ${None}

Comment >>

Web App State, line 108

LocalStorage Set Item

Save data to the local storage.

Arguments

NameDefaultType
keyrequiredstr
valuerequiredstr
frame_selector=NoneUnion

Tags

PageContentSetter

Documentation

Save data to the local storage.

Arguments Description
key The name of the key under which it should be saved.
value The value which shall be saved as a string.
frame_selector If this selector points to an element inside an iframe, the LocalStorage of that frame is used. Example: iframe[name="test"] >>> body

Example:

LocalStorage Set Item    Key    Value

Comment >>

Web App State, line 85

Merge Coverage Reports

Combines multiple raw coverage reports into a single report.

Arguments

NameDefaultType
input_folderrequiredPath
output_folderrequiredPath
config_file=NoneUnion
name=NoneUnion
reports=NoneUnion

Returns

Path

Tags

CoverageSetter

Documentation

Combines multiple raw coverage reports into a single report.

Arguments Description
input_folder Path to the base folder where the raw coverage reports are located.
output_folder Path to the folder where the combined report is stored.
config_file Optional path to options file
name Optional name for the combined report.
reports Optional list of reporters to create. Default is v8.

Returns the path to the output_folder.

The input_folder argument is the base folder where the coverage reports are located. The keyword will look into each subfolder and if the subfolder contains a "raw" folder, it will use the data from the "raw" folder for the combined report.

The output_folder argument is the folder where the combined report is saved. If the folder does not exist, it is created. If the folder exists, its content is deleted before the report is created.

The output_folder and input_folder must be full paths to the folders.

The config_file argument is optional and can be used to provide a path to a monocart-coverage-reports options file. If the file is defined but does not exist, the keyword fails. For more details see: https://www.npmjs.com/package/monocart-coverage-reports#config-file

The name argument is optional and can be used to provide a name for the combined report. If it is not defined, the report is named "Browser library Merged Coverage Report".

The reports argument is optional and can be used to provide a list of reporters to create. Default is v8.

The keyword combines only the raw reports. To get raw reports, the Start Coverage keyword must be called with the raw=True argument. If no raw reports are found from the input_folder, the keyword fails. The keyword should be used when there is a need to combine multiple reports into a single report. For example, when tests are run in multiple pages. The example below demonstrates how to use the keyword.

Example:

New PageStart CoverageGo To    ${LOGIN_URL}Test Feature X In The PageStop CoverageNew PageStart CoverageGo To    ${LOGIN_URL}Test Feature Y In The PageStop CoverageMerge Coverage Reports    ${OUTPUT_DIR}/browser/coverage    ${OUTPUT_DIR}/browser/combined-coverage

Coverage, line 128

Mouse Button

Clicks, presses or releases a mouse button.

Arguments

NameDefaultType
actionrequiredMouseButtonAction
x=NoneUnion
y=NoneUnion
button=leftMouseButton
clickCount=1int
delay=0:00:00Union

Tags

PageContentSetter

Documentation

Clicks, presses or releases a mouse button.

Arguments Description
action Defines if it is a mouseclick (click), holding down a button (down) or releasing it (up).
x, y Coordinates to move to before the action is executed. Both must be given, otherwise the action happens at the current mouse position.
button One of left, middle or right. Defaults to left.
clickCount Determines how often the button shall be clicked if action is equal to click. Defaults to 1.
delay Delay in Robot Framework time format between the mousedown and mouseup event. Can only be set if the action is click. Defaults to 0 s.

Attention: Argument type int for 'delay' in milliseconds has been changed to timedelta in Browser 14.0.0. Use Robot Framework time format instead. For refactoring just add 'ms' after the delay number.

Delay Example:

Mouse Button    click    delay=100 msMouse Button    click    delay=${dyn_delay} ms

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

Example:

Hover                     "Obstacle"           # Move mouse over the elementMouse Button              down                 # Press mouse button downMouse Move Relative To    "Obstacle"    500    # Drag mouseMouse Button              up                   # Release mouse button

Comment >>

Interaction, line 1038

Mouse Move

Moves the virtual mouse to the given coordinates, instead of to an element found by a selector.

Arguments

NameDefaultType
xrequiredfloat
yrequiredfloat
steps=1int

Tags

PageContentSetter

Documentation

Moves the virtual mouse to the given coordinates, instead of to an element found by a selector.

The virtual mouse is left on the specified coordinates.

Arguments Description
x & y Absolute coordinates starting at the top left of the page.
steps Number of intermediate steps for the mouse event. Often it is necessary to send more than one intermediate event to get the desired result. Defaults to 1.

Example:

Mouse Move    400    400

Comment >>

Interaction, line 1280

Mouse Move Relative To

Moves the mouse cursor relative to the selected element.

Arguments

NameDefaultType
selectorrequiredstr
x=0.0float
y=0.0float
steps=1int

Tags

PageContentSetter

Documentation

Moves the mouse cursor relative to the selected element.

Arguments Description
selector Identifies the element whose center is the start-point.
x & y Coordinates relative to the center of the element's bounding box.
steps Number of intermediate steps for the mouse event. Often it is necessary to send more than one intermediate event to get the desired result. Defaults to 1.

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

Example:

Mouse Move Relative To    id=indicator    -100

Comment >>

Interaction, line 1237

Mouse Wheel

Simulates the user rotation of a mouse wheel.

Arguments

NameDefaultType
deltaXrequiredint
deltaYrequiredint

Tags

PageContentSetter

Documentation

Simulates the user rotation of a mouse wheel.

Arguments Description
deltaX & deltaY Pixels that are scrolled horizontally & vertically.

Example:

# Before doing a mouse wheel interaction. A mouse needs to be positioned on the browser window.Hover    bodyMouse Wheel    0    250

Comment >>

Interaction, line 1301

New Browser

Create a new playwright Browser with specified options.

Arguments

NameDefaultType
browser=chromiumSupportedBrowsers
headless=Truebool
argsnamed only=NoneUnion
channelnamed only=NoneUnion
chromiumSandboxnamed only=Falsebool
devtoolsnamed only=Falsebool
downloadsPathnamed only=NoneUnion
envnamed only=NoneUnion
executablePathnamed only=NoneUnion
firefoxUserPrefsnamed only=NoneUnion
handleSIGHUPnamed only=Truebool
handleSIGINTnamed only=Truebool
handleSIGTERMnamed only=Truebool
ignoreDefaultArgsnamed only=NoneUnion
proxynamed only=NoneUnion
reuse_existingnamed only=Truebool
slowMonamed only=0:00:00timedelta
timeoutnamed only=0:00:30timedelta

Returns

str

Tags

BrowserControlSetter

Documentation

Create a new playwright Browser with specified options.

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

Returns a stable identifier for the created browser.

Arguments Description
browser Opens the specified browser. Defaults to chromium.
headless Set to False if you want a GUI. Defaults to True.
args Additional arguments to pass to the browser instance. The list of Chromium flags can be found here. Defaults to None.
channel Allows operating against the stock Google Chrome and Microsoft Edge browsers. Can only be used together with the chromium browser, otherwise the keyword fails. For more details see: Playwright documentation.
chromiumSandbox Enable Chromium sandboxing. Defaults to False.
devtools Chromium-only. Whether to auto-open a Developer Tools panel for each tab. Defaults to False.
downloadsPath If specified, accepted downloads are downloaded into this folder. Otherwise, temporary folder is created and is deleted when browser is closed. Regarding file deletion, see the docs of Download and Promise To Wait For Download.
env Specifies environment variables that will be visible to the browser. Dictionary keys are variable names, values are the content. Defaults to None.
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.
firefoxUserPrefs |Firefox user preferences. Learn more about the Firefox user preferences at about:config.
handleSIGHUP Close the browser process on SIGHUP. Defaults to True.
handleSIGINT Close the browser process on Ctrl-C. Defaults to True.
handleSIGTERM Close the browser process on SIGTERM. Defaults to True.
ignoreDefaultArgs If True, Playwright does not pass its own configuration args and only uses the ones from args. If a list is given, then the given default arguments are filtered out. Dangerous option; use with care. Defaults to None, which means Playwright's own default arguments are used.
proxy | Network Proxy settings. Structure: {'server': <str>, 'bypass': <Optional[str]>, 'username': <Optional[str]>, 'password': <Optional[str]>}. Robot Framework 7.4 Secret type is supported.|reuse_existing | If set to True, an existing browser instance that was created with the same arguments is reused. If no such browser exists, a new one is started. Defaults to True. |slowMo | Slows down Playwright operations by the given time, in Robot Framework time format. Useful so that you can see what is going on. Defaults to no delay. |timeout | Maximum time in Robot Framework time format to wait for the browser instance to start. Defaults to 30 seconds. Pass 0 to disable timeout. |

Comment >>

Browser, Context & Page, line 428

New Context

Create a new BrowserContext with specified options.

Arguments

NameDefaultType
acceptDownloadsnamed only=Truebool
baseURLnamed only=NoneUnion
bypassCSPnamed only=Falsebool
clientCertificatesnamed only=NoneUnion
colorSchemenamed only=NoneUnion
defaultBrowserTypenamed only=NoneUnion
deviceScaleFactornamed only=NoneUnion
extraHTTPHeadersnamed only=NoneUnion
forcedColorsnamed only=noneForcedColors
geolocationnamed only=NoneUnion
hasTouchnamed only=NoneUnion
httpCredentialsnamed only=NoneUnion
ignoreHTTPSErrorsnamed only=Falsebool
isMobilenamed only=NoneUnion
javaScriptEnablednamed only=Truebool
localenamed only=NoneUnion
offlinenamed only=Falsebool
permissionsnamed only=NoneUnion
proxynamed only=NoneUnion
recordHarnamed only=NoneUnion
recordVideonamed only=NoneUnion
reducedMotionnamed only=no_preferenceReduceMotion
screennamed only=NoneUnion
serviceWorkersnamed only=allowUnion
storageStatenamed only=NoneUnion
timezoneIdnamed only=NoneUnion
tracingnamed only=NoneUnion
userAgentnamed only=NoneUnion
viewportnamed only={'width': 1280, 'height': 720}Union

Returns

str

Tags

BrowserControlSetter

Documentation

Create a new BrowserContext with specified options.

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.

Arguments Description
acceptDownloads Whether to automatically download all the attachments. Defaults to True where all the downloads are accepted.
baseURL When using Go To, Wait For Request, Wait For Response or Wait For Navigation it takes the base URL in consideration by using the URL() constructor for building the corresponding URL. Unset by default. Examples: baseURL=http://localhost:3000 and navigating to /bar.html results in http://localhost:3000/bar.html. baseURL=http://localhost:3000/foo/ and navigating to ./bar.html results in http://localhost:3000/foo/bar.html. baseURL=http://localhost:3000/foo (without trailing slash) and navigating to ./bar.html results in http://localhost:3000/bar.html.
bypassCSP Toggles bypassing page's Content-Security-Policy. Defaults to False.
clientCertificates Specifies a client certificate for mTLS authentication, for example clientCertificates=[{'origin': 'https://playwright.dev', 'pfxPath': 'certificate.p12', 'passphrase': 'password'}]. NOTE: The origin needs to be exact without any path.
colorScheme Emulates the prefers-color-scheme media feature, supported values are light, dark, no-preference and null. null disables the emulation.
defaultBrowserType If no browser is open and New Context opens a new browser with defaults, this setting defines which browser is opened. Very useful together with the Get Device keyword.
deviceScaleFactor Specify device scale factor (can be thought of as dpr). Defaults to 1.
extraHTTPHeaders A dictionary containing additional HTTP headers to be sent with every request. All header values must be strings.
forcedColors Emulates the forced-colors media feature, supported values are active, none and null. Defaults to none.
geolocation A dictionary containing latitude and longitude and optionally accuracy to emulate. If latitude or longitude is not specified, the device geolocation won't be overridden.
hasTouch Specifies if viewport supports touch events. Defaults to False.
httpCredentials Credentials for HTTP authentication.
ignoreHTTPSErrors Whether to ignore HTTPS errors during navigation. Defaults to False.
isMobile Whether the meta viewport tag is taken into account and touch events are enabled. Defaults to False.
javaScriptEnabled Whether or not to enable JavaScript in the context. Defaults to True.
locale Specify user locale, for example en-GB, de-DE, etc.
offline Toggles browser's offline mode. Defaults to False.
permissions A list containing permissions to grant to all pages in this context. All permissions that are not listed here will be automatically denied.
proxy Network proxy settings to use with this context. Defaults to None. NOTE: For Chromium on Windows the 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, for example proxy={ server: 'http://per-context' }.
recordHar Enables HAR recording for all pages into a file. The path key must be a path to a file, for example recordHar={'path': '${OUTPUT_DIR}/har.file'}. If not specified, the HAR is not recorded. Make sure to close the context for the HAR to be saved.
recordVideo Enables video recording for all pages into a folder. If not specified videos are not recorded. Make sure to close the context for videos to be saved. Video is not supported in remote browsers.
reducedMotion Emulates the prefers-reduced-motion media feature, supported values are reduce and no-preference. Defaults to no-preference.
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}
serviceWorkers Whether to allow sites to register Service workers. Defaults to allow.
storageState Restores the storage state created by the Save Storage State keyword. Must be a path to an existing file, otherwise the keyword fails. Relative paths are resolved against the current working directory.
timezoneId Changes the timezone of the context. See ICU`s metaZones.txt for a list of supported timezone IDs.
tracing Boolean True (recommendation) or file path or directory where the tracing file is saved. The string {contextid} will be replaced with the context id. Path to *.zip files can be absolute or relative to ${OUTPUT_DIR}. Path to folders can be absolute or relative to ${OUTPUT_DIR}/browser/traces. If boolean True or a directory is given, the trace file will automatically be named trace_{contextid}.zip. Temporary trace files will be saved to ${OUTPUT_DIR}/browser/traces/temp. 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 /path/to/trace.zip. Tracing can also be enabled by setting a Robot Framework variable or environment variable ROBOT_FRAMEWORK_BROWSER_TRACING to True.
userAgent Specific user agent to use in this context.
viewport A dictionary containing width and height. Emulates consistent viewport for each page. Defaults to 1280x720. None disables the default viewport. If width and height are 0, the viewport will scale with the window.

Example:

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. It is not possible to create a new context in a browser that was opened with New Persistent Context.

The httpCredentials and proxy arguments do support Robot Framework 7.4 Secret type. If Secret is used, the dictionary structure must be created before hand, example with Robot Framework's VAR syntax:

${user}   ${password} =    Get Secrets    # Returns username and password as Robot Framework Secret typeVAR    &{httpCredentials} =    username=${user}    password=${password}New Context    httpCredentials=${httpCredentials}

Using dictionary literals with Robot Framework 7.4 Secret type is not supported, for example this will fail on variable conversion on Robot Framework side:

${user}   ${password} =    Get Secrets    # Returns username and password as Robot Framework Secret typeNew Context    httpCredentials={'username': ${secret}, 'password': ${secret}}    # This will fail

Comment >>

Browser, Context & Page, line 586

New Page

Open a new Page.

Arguments

NameDefaultType
url=NoneUnion
wait_until=loadPageLoadStates

Tags

BrowserControlSetter

Documentation

Open a new Page.

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

Arguments Description
url Optional URL to navigate the page to. The url should include the protocol, for example https://.
wait_until 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.

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.

If navigating to url fails, the newly created page is closed again and the keyword fails.

Comment >>

Browser, Context & Page, line 991

New Persistent Context

Opens a new persistent context.

Arguments

NameDefaultType
userDataDir=str
browser=chromiumSupportedBrowsers
headless=Truebool
acceptDownloadsnamed only=Truebool
argsnamed only=NoneUnion
baseURLnamed only=NoneUnion
bypassCSPnamed only=Falsebool
channelnamed only=NoneUnion
chromiumSandboxnamed only=Falsebool
colorSchemenamed only=NoneUnion
defaultBrowserTypenamed only=NoneUnion
deviceScaleFactornamed only=NoneUnion
devtoolsnamed only=Falsebool
downloadsPathnamed only=NoneUnion
envnamed only=NoneUnion
executablePathnamed only=NoneUnion
extraHTTPHeadersnamed only=NoneUnion
forcedColorsnamed only=noneForcedColors
geolocationnamed only=NoneUnion
handleSIGHUPnamed only=Truebool
handleSIGINTnamed only=Truebool
handleSIGTERMnamed only=Truebool
hasTouchnamed only=NoneUnion
httpCredentialsnamed only=NoneUnion
ignoreDefaultArgsnamed only=NoneUnion
ignoreHTTPSErrorsnamed only=Falsebool
isMobilenamed only=NoneUnion
javaScriptEnablednamed only=Truebool
localenamed only=NoneUnion
offlinenamed only=Falsebool
permissionsnamed only=NoneUnion
proxynamed only=NoneUnion
recordHarnamed only=NoneUnion
recordVideonamed only=NoneUnion
reducedMotionnamed only=no_preferenceReduceMotion
screennamed only=NoneUnion
serviceWorkersnamed only=allowUnion
slowMonamed only=0:00:00timedelta
timeoutnamed only=0:00:30timedelta
timezoneIdnamed only=NoneUnion
tracingnamed only=NoneUnion
urlnamed only=NoneUnion
userAgentnamed only=NoneUnion
viewportnamed only={'width': 1280, 'height': 720}Union

Documentation

Opens a new persistent context.

New Persistent Context basically executes New Browser, New Context and New Page in one step and sets a profile at the same time. See persistent context in Playwright docs.

This keyword returns a tuple of browser id, context id and page details. (New in Browser 15.0.0)

Argument Description
userDataDir Path to a User Data Directory, which stores browser session data like cookies and local storage. 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.
browser Browser type to use. Default is Chromium.
headless Whether to run browser in headless mode. Defaults to True.
other arguments Please see New Browser, New Context and New Page for more information about the other arguments.

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"]${browserId}  ${contextId}  ${pageDetails}=  New Persistent Context  browser=chromium  headless=False  url=https://robocon.io  args=${launch_args}

Check New Browser, New Context and New Page for the specific argument docs.

Comment >>

Browser, Context & Page, line 718

Open Browser

Opens a new browser instance. Use this keyword for quick experiments or debugging sessions.

Arguments

NameDefaultType
url=NoneUnion
browser=chromiumSupportedBrowsers
headless=Falsebool
pause_on_failure=Truebool
bypassCSP=True

Tags

BrowserControlSetter

Documentation

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.

Creates a new browser, context and page with specified settings.

Argument Description
url Navigates to URL if provided. Defaults to None.
browser Specifies which browser to use. The supported browsers are listed in the table below.
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.

Browsers:

Value Name(s)
firefox Firefox
chromium Chromium
webkit webkit

Comment >>

Browser, Context & Page, line 76

Pause At

Advances the clock by jumping forward in time and pauses it.

Arguments

NameDefaultType
timerequireddatetime

Tags

ClockSetter

Documentation

Advances the clock by jumping forward in time and pauses it.

Arguments Description
time The time to pause the clock at.

Fires due timers at most once. This is equivalent to a user closing the laptop lid for a while and reopening it at the specified time and then pausing. Pause can not move the clock backwards.

Example:

Set Time         2024-10-31 17:34:00    # Set the clock to a specific timeDo Something                            # Implement this in your keywordPause At         2024-10-31 18:34:00    # Pause the clock at a specific timeCheck Something                         # Also this is implemented in your keywordResume Clock                            # Resume the clockDo Something Else                       # Do something after clock runs normally

Clock, line 69

Press Keys

Types the given key combination into element found by selector.

Arguments

NameDefaultType
selectorrequiredstr
*keysstr
press_durationnamed only=0:00:00timedelta
key_delaynamed only=0:00:00timedelta

Tags

PageContentSetter

Documentation

Types the given key combination into element found by selector.

Arguments Description
selector Selector of the text field. See the Finding elements section for details about the selectors.
*keys Keys to be pressed one after the other. Combining modifiers with a single key press by chaining them with +, like Control+Shift+T, is supported.
press_duration Delay between keydown and keyup of each key. Can be given as seconds (float) or as Robot Framework time string. Defaults to 0 ms. Example: 50 ms
key_delay Delay between key presses. Can be given as seconds (float) or as Robot Framework time string. Defaults to 0 ms. Example: 50 ms

Supports values like a or b which will be automatically typed.

Also supports identifiers for keys like ArrowLeft or Backspace.

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

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

Example:

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

Comment >>

Interaction, line 274

Promise To

Wrap a Browser library keyword and make it a promise.

Arguments

NameDefaultType
kwrequiredstr
*args

Returns

Future

Tags

Wait

Documentation

Wrap a Browser library keyword and make it a promise.

The promised keyword is started in the background. Test execution continues without waiting for kw to finish.

Returns a reference to the promised keyword. Use Wait For or Wait For All Promises to wait for its result. Promises that are never waited for are waited for automatically at the end of the test, and a warning is logged.

Only Browser library keywords can be promised, any other keyword name fails the keyword.

Arguments Description
kw Keyword that will run asynchronously in the background.
*args Keyword arguments as normally used.

Example:

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

Comment >>

Promises, line 39

Promise To Upload File

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

Arguments

NameDefaultType
pathrequiredPathLike

Returns

Future

Tags

PageContentSetter

Documentation

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

The file from path is uploaded into the next file chooser dialog on the page.

The keyword fails immediately if path does not point to an existing file. The promise fails if no file chooser dialog is opened within the timeout.

Arguments Description
path Path to file to be uploaded.

Example use:

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

Alternatively, you can use the Upload File By Selector keyword.

Comment >>

Promises, line 280

Promise To Wait For Download

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

Arguments

NameDefaultType
saveAs=str
wait_for_finished=Truebool
download_timeout=NoneUnion

Returns

Future

Tags

BrowserControlWait

Documentation

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

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

With the default file path downloaded files are deleted when the context the download happened in is closed.

If browser is connected remotely with Connect To Browser then saveAs must be set to store it locally where the browser runs!

Arguments Description
saveAs Defines path where the file is saved persistently. File will also temporarily be saved in playwright context's default download location. If empty, generated unique path (GUID) is used and file is deleted when the context is closed.
wait_for_finished If true, promise will wait for download to finish. If false, promise will resolve immediately after download has started.
download_timeout Maximum time to wait for the download to finish, if wait_for_finished is set to True. If the download is not finished within this time, it is cancelled and the keyword fails. If not set, the keyword waits until the download is finished.

Keyword returns dictionary of type DownloadInfo which contains downloaded file path and suggested filename as well as state and downloadID. Example:

{  "saveAs": "/tmp/robotframework-browser/downloads/2f1b3b7c-1b1b-4b1b-9b1b-1b1b1b1b1b1b",  "suggestedFilename": "downloaded_file.txt",  "state": "finished",  "downloadID": None}

If wait_for_finished is False, saveAs is an empty string, state is in_progress and downloadID contains an id which can be used with Get Download State to check the download later.

The keyword New Browser has a downloadsPath setting which can be used to set the default download directory. If saveAs is set to a relative path, the file will be saved relative to the browser's downloadsPath setting or if that is not set, relative to the Playwright's working directory. If saveAs is set to an absolute path, the file will be saved to that absolute path independent of downloadsPath.

If the URL for the file to download shall be used, Download keyword may be a simpler alternative way to download the file.

The waited promise returns a dictionary which contains saveAs and suggestedFilename as keys. The saveAs contains the location where the file is downloaded and suggestedFilename contains the 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=TrueNew Page               ${LOGIN_URL}${dl_promise}          Promise To Wait For Download    /path/to/download/file.nameClick                  id=file_download${file_obj}=           Wait For    ${dl_promise}File Should Exist      ${file_obj}[saveAs]Should Be True         ${file_obj.suggestedFilename}

Comment >>

Promises, line 144

Record Selector

Record the selector that is under mouse.

Arguments

NameDefaultType
label=NoneUnion

Tags

PageContent

Documentation

Record the selector that is under mouse.

Arguments Description
label Text to show in the box on the page while recording.

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

Example:

${selector} =    Record Selector   ButtonClick  ${selector}${selector2} =    Record Selector  Page headerGet Text  ${selector2}  ==  Expected text

Comment >>

Interaction, line 486

Register Keyword To Run On Failure

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

Arguments

NameDefaultType
keywordrequiredUnion
*argsstr
scopenamed only=GlobalScope

Returns

DelayedKeyword

Tags

Config

Documentation

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

Arguments Description
keyword 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 The arguments to the keyword if any.
scope Scope defines the lifetime of this setting. Available values are Global, Suite or Test / Task. See Scope Setting for more details.

The initial keyword to use is set when importing the library, and the keyword that is used by default is Take Screenshot fail-screenshot-{index}. 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 previously registered failure keyword. The return value can always be used to restore the original value later. The returned object contains the keyword name and the possible arguments used for the keyword.

If the Take Screenshot keyword is registered as run on failure keyword without positional arguments and without the filename argument, then the default value of the filename argument is not used as screenshot file name. Instead, ${TEST NAME}_FAILURE_SCREENSHOT_{index} in the output directory is used as file name. If there is a need to use the default value of the filename argument, use robotframework-browser-screenshot-{index} as the filename argument value.

Example:

Register Keyword To Run On Failure    Take Screenshot    # Uses ${TEST NAME}_FAILURE_SCREENSHOT_{index} as filenameRegister Keyword To Run On Failure    Take Screenshot    robotframework-browser-screenshot-{index}    # Uses robotframework-browser-screenshot-{index} as filename${previous kw}=    Register Keyword To Run On Failure    NONE    # Disables run on failure functionality.Register Keyword To Run On Failure    ${previous kw}Register Keyword To Run On Failure    Take Screenshot    fullPage=TrueRegister Keyword To Run On Failure    Take Screenshot    failure-{index}    fullPage=True

Comment >>

Run On Failure, line 29

Reload

Reloads current active page.

Arguments

NameDefaultType
timeout=NoneUnion
waitUntil=loadPageLoadStates

Tags

BrowserControlSetter

Documentation

Reloads current active page.

Arguments Description
timeout Maximum time for the reload to succeed. If not given, the currently set browser timeout is used.
waitUntil When to consider the operation succeeded, defaults to load.

waitUntil events can be either: domcontentloaded - consider the operation to be finished when the DOMContentLoaded event is fired. load - consider the operation to be finished when the load event is fired. networkidle - consider the operation to be finished when there are no network connections for at least 500 ms. commit - consider the operation to be finished when the network response is received and the document started loading.

Comment >>

Browser Control, line 592

Remove Locator Handler

Remove the locator handler indicated by locator.

Arguments

NameDefaultType
locatorrequiredstr

Tags

PageContentSetter

Documentation

Remove the locator handler indicated by locator.

The locator must be exactly the same string that was used as the selector argument when the handler was added. Handlers are tied to the page in which they were added, therefore this keyword removes the handler from the active page only. If no handler is found, the keyword does not fail, it only logs that no handler was found.

Locator Handlers, line 91

Resume Clock

Resumes the clock.

Takes no arguments.

Tags

ClockSetter

Documentation

Resumes the clock.

Once this keyword is called, time resumes flowing and timers are fired as usual.

Clock, line 57

Save Page As Pdf

Saves page as PDF.

Arguments

NameDefaultType
pathrequiredPathLike
displayHeaderFooternamed only=Falsebool
footerTemplatenamed only=str
formatnamed only=LetterPdfFormat
headerTemplatenamed only=str
heightnamed only=0pxstr
landscapenamed only=Falsebool
marginnamed only={'top': '0px', 'right': '0px', 'bottom': '0px', 'left': '0px'}PdfMarging
outlinenamed only=Falsebool
pageRangesnamed only=str
preferCSSPageSizenamed only=Falsebool
printBackgroundnamed only=Falsebool
scalenamed only=1float
taggednamed only=Falsebool
widthnamed only=0pxstr

Returns

str

Tags

GetterPageContent

Documentation

Saves page as PDF.

Saving a PDF is currently only supported in Chromium and only when the browser is running in headless mode.

Arguments Description
path Where the PDF is saved. If the path is not absolute, the file is saved relative to ${OUTPUT_DIR}.
displayHeaderFooter Display header and footer. Defaults to false.
footerTemplate HTML template for the print footer. Should use the same format as the headerTemplate.
format Paper format. If set, takes priority over the width and height arguments. Defaults to Letter.
headerTemplate HTML template for the print header. Both templates are only rendered when displayHeaderFooter is true. See the detailed explanation below.
height Paper height, accepts values labeled with units.
landscape Paper orientation. Defaults to false.
margin Defines the PDF margins, see PdfMarging for more details. Defaults to 0px on all sides.
outline Whether or not to embed the document outline into the PDF. Defaults to false.
pageRanges Paper ranges to print, e.g. 1-5, 8, 11-13. Defaults to the empty string, which means print all pages.
preferCSSPageSize Give any CSS @page size declared in the page priority over what is declared in the width and height or format arguments. Defaults to false, which will scale the content to fit the paper size.
printBackground Print background graphics. Defaults to false.
scale Scale of the webpage rendering. Defaults to 1. Scale amount must be between 0.1 and 2.
tagged Whether or not to generate a tagged (accessible) PDF. Defaults to false.
width Paper width, accepts values labeled with units.

headerTemplate and footerTemplate should be valid HTML markup. The following classes can be used to inject printing values into them:

  • date formatted print date
  • title document title
  • url document location
  • pageNumber current page number
  • totalPages total pages in the document

All possible units are:

  • px - pixel
  • in - inch
  • cm - centimeter
  • mm - millimeter

headerTemplate and footerTemplate markup have the following limitations:

  • Script tags inside the templates are not evaluated.
  • Page styles are not visible inside the templates.

Returns the path to the saved PDF file.

More details can be found in the Playwright pdf documentation.

Example:

New Browser        Chromium              headless=TrueNew Page           ${URL}Emulate Media      media=screen${pdf_path} =      Save Page As Pdf    page.pdfShould Be Equal    ${pdf_path}           ${OUTPUT_DIR}${/}page.pdf

PDF, line 42

Save Storage State

Saves the current active context storage state to a file.

Arguments

NameDefaultType
path=NoneUnion
indexedDBnamed only=Falsebool
credentialsnamed only=Falsebool

Returns

str

Tags

BrowserControlGetter

Documentation

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. This keyword retrieves the storage state from authenticated contexts and saves it to disk. Then New Context can be created with prepopulated state.

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

Arguments Description
path Where the state file is written. Relative paths are resolved against the current working directory and missing parent directories are created. If the file already exists, it is overwritten. If not given, a file with a generated name is created in ${OUTPUTDIR}/browser/state. The absolute path of the written file is returned.
indexedDB Also save IndexedDB. Needed by applications, like Firebase, which store authentication tokens in IndexedDB.
credentials Also save the context's virtual WebAuthn credentials, as created by Create Credential. This is not related to the httpCredentials argument of New Context, which is about HTTP authentication.

Files in ${OUTPUTDIR}/browser/state are automatically deleted when new test execution starts. To keep a state file over several executions, save it with path to a location outside of that folder. File path is returned by the keyword.

Example:

Test Case    New context    New Page    https://login.page.html    #  Perform login    VAR    ${username: Secret}    %{USERNAME}    # Convert environment variable to secret    VAR    ${password: Secret}    %{PASSWORD}    # Convert environment variable to secret    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 >>

Browser, Context & Page, line 1689

Scroll By

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

Arguments

NameDefaultType
selector=NoneUnion
vertical=heightstr
horizontal=0str
behavior=autoScrollBehavior

Tags

PageContentSetter

Documentation

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

Arguments Description
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 scroll exactly one visible height down, or -height to scroll one visible height up. 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. Defaults to height.
horizontal Defines how far and in which direction to scroll horizontally. Works the same way as vertical, but positive values scroll to the right and negative values to the left. width scrolls exactly one visible range to the right. Defaults to 0.
behavior Defines whether the scroll happens instantly or smoothly. Defaults to auto.

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

Comment >>

Interaction, line 631

Scroll To

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

Arguments

NameDefaultType
selector=NoneUnion
vertical=topstr
horizontal=leftstr
behavior=autoScrollBehavior

Tags

PageContentSetter

Documentation

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

Arguments Description
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 the 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 currently known bottom coordinate. Defaults to top.
horizontal Defines where to scroll horizontally. Works the same way as vertical, but defines < left right > as start and end. Defaults to left.
behavior Defines whether the scroll happens instantly or smoothly. Defaults to auto.

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

Comment >>

Interaction, line 590

Scroll To Element

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

Arguments

NameDefaultType
selectorrequiredstr

Tags

PageContentSetter

Documentation

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

Arguments Description
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.

Does nothing if the element is already completely visible.

Comment >>

Interaction, line 672

Select Options By

Selects options from select element found by selector.

Arguments

NameDefaultType
selectorrequiredstr
attributerequiredSelectAttribute
*values

Returns

list

Tags

PageContentSetter

Documentation

Selects options from select element found by selector.

Arguments Description
selector Selector of the <select> tag. See the Finding elements section for details about the selectors.
attribute Attribute to select options by. Can be value, label, text or index. Where label and text are same.
*values Values to select.

Returns a list of the options which the keyword was able to select. The type of the list items matches the attribute definition. For example, if attribute equals label, the returned list contains label values. Or in case of index, it contains the selected indexes.

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

If no values to select are passed, all options of the element are deselected. The keyword fails if none of the given values matches an option.

Example:

${selected} =    Select Options By    select[name=preferred_channel]    label    Direct mailList Should Contain Value    ${selected}    Direct mail${selected} =    Select Options By    select[name=interests]    value    males    females    othersList Should Contain Value    ${selected}    malesList Should Contain Value    ${selected}    femalesList Should Contain Value    ${selected}    othersLength Should Be    ${selected}    3${selected} =    Select Options By    select[name=possible_channels]    index    0    2List Should Contain Value    ${selected}    0List Should Contain Value    ${selected}    2${selected} =    Select Options By    select[name=interests]    text     Males    FemalesList Should Contain Value    ${selected}    MalesList Should Contain Value    ${selected}    Females

Comment >>

Interaction, line 739

SessionStorage Clear

Remove all saved data from the session storage.

Arguments

NameDefaultType
frame_selector=NoneUnion

Tags

PageContentSetter

Documentation

Remove all saved data from the session storage.

Arguments Description
frame_selector If this selector points to an element inside an iframe, the SessionStorage of that frame is used. Example: iframe[name="test"] >>> body

Example:

SessionStorage Set Item    mykey3    myvalue3SessionStorage ClearSessionStorage Get Item    mykey3    ==    ${None}

Comment >>

Web App State, line 236

SessionStorage Get Item

Get saved data from the session storage.

Arguments

NameDefaultType
keyrequiredstr
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion
frame_selector=NoneUnion

Returns

Any

Tags

AssertionGetterPageContent

Documentation

Get saved data from the session storage.

Arguments Description
key Named key of the item in the storage.
assertion_operator Assertion operator to use. See Assertions for more information.
assertion_expected Expected value to compare with.
message Custom error message to use.
frame_selector If this selector points to an element inside an iframe, the SessionStorage of that frame is used. Example: iframe[name="test"] >>> body

See Assertions for further details about the assertion arguments. They default to None.

If the key does not exist in the storage, ${None} is returned.

Example:

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

Comment >>

Web App State, line 151

SessionStorage Remove Item

Remove saved data with key from the session storage.

Arguments

NameDefaultType
keyrequiredstr
frame_selector=NoneUnion

Tags

PageContentSetter

Documentation

Remove saved data with key from the session storage.

Arguments Description
key The name of the item which shall be deleted.
frame_selector If this selector points to an element inside an iframe, the SessionStorage of that frame is used. Example: iframe[name="test"] >>> body

Example:

SessionStorage Set Item       mykey2    myvalue2SessionStorage Remove Item    mykey2SessionStorage Get Item       mykey2    ==    ${None}

Comment >>

Web App State, line 216

SessionStorage Set Item

Save data to session storage.

Arguments

NameDefaultType
keyrequiredstr
valuerequiredstr
frame_selector=NoneUnion

Tags

PageContentSetter

Documentation

Save data to session storage.

Arguments Description
key The name of the key under which it should be saved.
value The value which shall be saved as a string.
frame_selector If this selector points to an element inside an iframe, the SessionStorage of that frame is used. Example: iframe[name="test"] >>> body

Example:

SessionStorage Set Item    key2    value2

Comment >>

Web App State, line 194

Set Assertion Formatters

Set keywords formatters for assertions.

Arguments

NameDefaultType
formattersrequiredDict
scope=SuiteScope

Returns

dict

Tags

Config

Documentation

Set keywords formatters for assertions.

Arguments Description
formatters Dictionary of keywords and formatters, where the key is the name of the keyword where the formatters are applied. The dictionary value is a list of formatters which are applied. Formatters for a defined keyword are always overwritten. An empty list will clear all formatters for the keyword. If formatters is an empty dictionary, then all formatters are cleared from all keywords, in the Global scope, regardless of the scope argument.
scope Defines the lifetime of the formatter, possible values are Global, Suite and Test.

Returns the formatters which were in use before this keyword was called. Formatters defined as lambda functions are not included in the returned value.

See type documentation of FormatterKeywords and FormatingRules for more information.

It is possible to define own formatters as lambda functions.

Example:

Set Assertion Formatters    {"Get Text": ["strip", "normalize spaces"]}  # This will convert all kinds of spaces to a single space and remove spaces from the start and end of the string.Set Assertion Formatters    {"Get Title": ["apply to expected","lambda x: x.replace(' ', '')"]}  # This will remove all spaces from the string.${value} =    Get Text    //div    ==    ${SPACE}Expected${SPACE * 2}TextShould Be Equal    ${value}    Expected Text

Comment >>

Assertion Formatter, line 79

Set Browser Timeout

Sets the timeout used by most input and getter keywords.

Arguments

NameDefaultType
timeoutrequiredtimedelta
scope=SuiteScope

Returns

str

Tags

ConfigSetter

Documentation

Sets the timeout used by most input and getter keywords.

Arguments Description
timeout The timeout is set for the current Playwright context and for new contexts. Supports Robot Framework time format.
scope Scope defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope Setting for more details.

Returns the previous value of the timeout.

Example:

${old_timeout} =    Set Browser Timeout    1m 30 secondsClick     //buttonSet Browser Timeout    ${old_timeout}

Comment >>

Browser Control, line 370

Set Geolocation

Updates the current context's geolocation.

Arguments

NameDefaultType
latituderequiredfloat
longituderequiredfloat
accuracy=NoneUnion

Tags

BrowserControlSetter

Documentation

Updates the current context's geolocation.

Latitude can be between -90 and 90 and longitude can be between -180 and 180. The accuracy of the location must be a non-negative number and defaults to 0. When creating the context, grant the geolocation permission so that pages can read the geolocation.

Arguments Description
latitude Latitude between -90 and 90.
longitude Longitude between -180 and 180.
accuracy Non-negative accuracy value. Defaults to 0.

Example:

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

Comment >>

Browser Control, line 561

Set Highlight On Failure

Controls if the element is highlighted on failure.

Arguments

NameDefaultType
highlight=Truebool
scope=SuiteScope

Returns

bool

Tags

ConfigSetter

Documentation

Controls if the element is highlighted on failure.

Arguments Description
highlight If True, the element is highlighted when a screenshot is taken on failure. If False, the element is not highlighted in the screenshot.
scope Scope defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope for more details.

Returns the previous value of the setting.

Example:

Set Highlight On Failure    True

Comment >> #TODO add real link

Browser Control, line 468

Set Offline

Toggles the current context's offline emulation.

Arguments

NameDefaultType
offline=Truebool

Tags

BrowserControlSetter

Documentation

Toggles the current context's offline emulation.

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

Comment >>

Browser Control, line 548

Set Presenter Mode

Sets presenter mode for element highlighting during test execution.

Arguments

NameDefaultType
moderequiredUnion

Returns

Union

Tags

BrowserControlSetter

Documentation

Sets presenter mode for element highlighting during test execution.

Presenter mode highlights elements found by keywords, which is useful for test debugging and demonstration. When enabled, the element is scrolled into view and highlighted with a border for a while to visually show what the keyword found.

Arguments Description
mode When set to True, enables presenter mode with default settings. When set to False, disables presenter mode. Can also be a dictionary containing the highlighting configuration options as defined in HighLightElement. Fields which are not given use their default values: duration 2 seconds, width 2px, style dotted and color blue.

The keyword returns the previous presenter mode value, allowing you to restore it later.

Example:

${old_mode} =    Set Presenter Mode    TrueClick    //button                            # Element will be highlightedSet Presenter Mode    ${old_mode}            # Restore previous mode# With custom highlighting configurationVAR    &{config}...    duration=5 seconds...    width=3px...    style=dotted...    color=redSet Presenter Mode    ${config}Get Text    //input                          # Will use custom highlight settingsSet Presenter Mode    False                  # Turn off highlighting

Browser Control, line 651

Set Retry Assertions For

Sets the timeout used in retrying assertions when they fail.

Arguments

NameDefaultType
timeoutrequiredtimedelta
scope=SuiteScope

Returns

str

Tags

ConfigSetter

Documentation

Sets the timeout used in retrying assertions when they fail.

Arguments Description
timeout Assertion retry timeout will determine how long Browser library will retry an assertion to be true.
scope Scope defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope for more details.

The other keyword Set Browser Timeout controls how long Playwright will wait on the node side for elements to fulfill the requirements of the specific keyword.

Returns the previous value of the assertion retry timeout.

Example:

Set Browser Timeout    10 seconds${old} =    Set Retry Assertions For    30sGet Title    ==    Login PageSet Retry Assertions For    ${old}

The example waits 10 seconds in Playwright to get the page title and the library will retry for 30 seconds to make sure that the title is correct.

Comment >>

Browser Control, line 404

Set Selector Prefix

Sets the prefix for all selectors in the given scope.

Arguments

NameDefaultType
prefixrequiredUnion
scope=SuiteScope

Returns

str

Tags

ConfigSetter

Documentation

Sets the prefix for all selectors in the given scope.

Arguments Description
prefix Prefix for all selectors. Prefix and selector will be separated by a single space. Use ${None} or ${EMPTY} to disable the prefix.
scope Scope defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope for more details.

Returns the previous value of the prefix.

Example:

${old} =    Set Selector Prefix    iframe#embedded_page >>>Click    button#login_btn       # Clicks on button inside iframe with the selector iframe#embedded_page >>> button#login_btnSet Selector Prefix    ${old}

Example will click on button with id login_btn inside iframe with id embedded_page. The resulting selector will be iframe#embedded_page >>> button#login_btn.

The effect of this prefix can be disabled by prefixing any selector with !prefix , with a trailing space, for single keyword calls, i.e. !prefix id=btn_outside_a_frame

Get Element, Get Elements, Get Element By and Get Element By Role automatically prefix the returned selector with !prefix so that it is possible to use them directly without setting the prefix to ${None} before usage.

Comment >>

Browser Control, line 435

Set Storage State

Restores a storage state file into the current active context.

Arguments

NameDefaultType
pathrequiredPath
timeout=NoneUnion
reload_pages=affectedReloadPages

Tags

BrowserControlSetter

Documentation

Restores a storage state file into the current active context.

Clears the cookies, local storage, IndexedDB and virtual WebAuthn credentials of the currently active context and replaces them with the ones from the path file, which must have been created by Save Storage State. Unlike creating a New Context with the storageState argument, the context and all of its pages stay open.

Pages that are already open keep the state they have loaded into memory. Reload them, with the Reload keyword, to make them see the restored state. Cookies and local storage are readable right away, without a reload, but the application has read them long ago.

Note that sessionStorage is not part of a storage state, neither when saving nor when restoring. It survives this keyword unchanged, so an application which keeps data of the previous user there still has it after the state was replaced.

Restoring a state which was saved with credentials=True installs the virtual WebAuthn authenticator into the context, the same way Install Credential does. Real authenticators do not work in that context afterwards.

Arguments Description
path Path to a state file created by Save Storage State. Relative paths are resolved against the current working directory. The keyword fails if the file does not exist.
timeout Time to wait for the state to be restored. If not defined, the library default timeout is used. Pass 0 to disable the timeout.
reload_pages Which pages are reloaded while the state is restored, see ReloadPages. Only relevant when the state file contains IndexedDB.

Restoring IndexedDB

Restoring IndexedDB deletes the databases of the origin first, and that does not finish while any client of that origin holds an open connection to them. An application which keeps its connection open, which is the normal pattern when authentication tokens are stored in IndexedDB, therefore blocks the restore indefinitely. Playwright does not time out on its own, see playwright#42258.

This keyword works around that by navigating the pages of the affected origins to about:blank, restoring the state, and navigating them back to the url they had before. Use reload_pages to control which pages that applies to. A reload is needed in any case, because deleting the databases closes the connection of the application as well.

A service worker of the origin can hold a connection open too, and no value of reload_pages helps against that, because a service worker outlives the pages. The keyword then fails when timeout expires.

reload_pages=none detects a blocking connection up front and fails immediately instead of waiting for the timeout. That detection needs indexedDB.databases(), which older browsers, Firefox before 126 among them, do not have. There the keyword cannot tell whether a connection blocks and falls back to waiting for timeout.

Example:

New ContextNew Page    https://login.page.html    #  Perform login as first user${user_a} =    Save Storage State    indexedDB=True    #  Perform login as second user${user_b} =    Save Storage State    indexedDB=True    #  Switch back to the first user without creating a new contextSet Storage State    ${user_a}ReloadGet Text    id=current-user    ==    userA

Browser, Context & Page, line 1763

Set Strict Mode

Controls library strict mode.

Arguments

NameDefaultType
moderequiredbool
scope=SuiteScope

Tags

BrowserControlSetter

Documentation

Controls library strict mode.

Arguments Description
mode When set to True, keywords that search elements will use Playwright strict mode and fail if the selector matches more than one element. When set to False, such keywords do not fail but operate on the first matching element.
scope Scope defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope for more details.

The keyword returns the strict mode value which was in use before this keyword was called.

Strict mode is enabled by default. The initial value can also be set with the strict argument in the library importing. Strict mode is applied only to those keywords which state in their documentation that they use strict mode, see Finding elements for more details.

Example:

${old_mode} =      Set Strict Mode    FalseGet Text           //input            # Does not fail even if the selector matches multiple elementsSet Strict Mode    ${old_mode}

Comment >>

Strict Mode, line 20

Set Time

Sets the time of the browser's internal clock.

Arguments

NameDefaultType
timerequireddatetime
clock_type=installClockType

Tags

ClockSetter

Documentation

Sets the time of the browser's internal clock.

Arguments Description
time The time to set. Supports Robot Framework date and time format
clock_type The clock type to set. Default is install.

fixed makes Date.now and new Date() always return the same fake time, while all timers keep running.

system sets the current system time but does not trigger any timers.

install installs fake timers, which are used to manually control the flow of time in tests. They allow you to advance time, fire timers, and control the behavior of time-dependent functions.

How to use clock related keywords, see Playwright clock documentation. Also reviewing the Playwright Clock API is recommended.

Clock, line 23

Set Viewport Size

Sets the current page's viewport size to the specified dimensions.

Arguments

NameDefaultType
widthrequiredint
heightrequiredint

Tags

BrowserControlSetter

Documentation

Sets the current page's viewport size to the specified dimensions.

In the case of multiple pages in a single browser, each page can have its own viewport size. However, New Context allows setting the 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 with New Context before opening the page itself.

Arguments Description
width Sets the width in pixels.
height Sets the height in pixels.

Comment >>

Browser Control, line 522

Show Keyword Banner

Controls if the keyword banner is shown on page or not.

Arguments

NameDefaultType
show=Truebool
style=str
scope=SuiteScope

Returns

dict

Tags

ConfigSetter

Documentation

Controls if the keyword banner is shown on page or not.

The keyword call banner is a CSS overlay that shows the currently executed keyword directly on the page. This is useful for debugging and for showing the test execution on video recordings. By default, the banner is not shown on the page except when running in presenter mode.

The banner can also be controlled by an import setting of the Browser library. (see Importing section)

Arguments Description
show If True, the banner is shown on the page. If False, the banner is not shown on the page. If ${None}, the banner is shown on the page only when running in presenter mode.
style Additional CSS styles to be applied to the banner. These styles may override the existing ones for the banner.
scope Scope defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope for more details.

Returns the previous settings as a dictionary with the keys show and style.

Example:

Show Keyword Banner     True    top: 5px; bottom: auto; left: 5px; background-color: #00909077; font-size: 9px; color: black;   # Show banner on top left corner with custom stylesShow Keyword Banner     False   # Hide banner

Comment >>

Browser Control, line 489

Start Coverage

Starts the coverage for the current page.

Arguments

NameDefaultType
config_filenamed only=NoneUnion
coverage_typenamed only=allCoverageType
pathnamed only=.Path
rawnamed only=Falsebool
reportAnonymousScriptsnamed only=Falsebool
resetOnNavigationnamed only=Truebool

Returns

str

Tags

CoverageExperimentalSetter

Documentation

Starts the coverage for the current page.

Arguments Description
config_file Optional path to options file. If the file does not exist, it is ignored.
coverage_type Type of coverage to start. Default is all.
path Absolute or relative directory path (relative to ${OUTPUT_DIR}/browser/coverage/) where the coverage is stored in a directory with the page id name.
raw Whether to save raw coverage data. Default is False.
reportAnonymousScripts Whether to report anonymous scripts. Default is False. Only valid for JS coverage.
resetOnNavigation Whether to reset coverage on navigation. Default is True.

The coverage_type can be one of the following:

Coverage must be started when the page is open and before any action is performed on the page. Coverage will be stored when calling the Stop Coverage keyword or when the page or context is closed. This is done automatically when using the auto closing.

The raw argument saves the raw coverage data in the coverage folder. The raw data is needed to combine multiple coverage reports into a single report. A single report can be created with the rfbrowser coverage /path/to/basefolder/ /path/to/outputfolder/ command. Please note that the raw argument is ignored if the config_file is defined. In that case the user is responsible for also setting the raw reporter in the config file. To see more details about combining coverage data, run the rfbrowser coverage --help command.

Example:

New PageStart CoverageGo To    ${LOGIN_URL}Do Something In The PageStop Coverage

Coverage, line 28

Stop Coverage

Stops the coverage for the current page.

Takes no arguments.

Returns

Union

Tags

CoverageGetter

Documentation

Stops the coverage for the current page.

Creates a coverage report by using monocart-coverage-reports To see the default and all possible options, see options.js file for more details.

If coverage was not started, the keyword returns None. Otherwise it returns the path to the generated HTML report file, or the path to the coverage folder if no HTML file is found from the folder. The latter can happen when the report format or output folder has been changed with the config_file argument of the Start Coverage keyword.

Coverage, line 91

Switch Browser

Switches the currently active Browser to another open Browser.

Arguments

NameDefaultType
idrequiredstr

Returns

str

Tags

BrowserControlSetter

Documentation

Switches the currently active Browser to another open Browser.

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

Arguments Description
id The id of the browser to switch to. Example: browser=96207191-8147-44e7-b9ac-5e04f2709c1d. A browser id is returned by New Browser when it is started or can be fetched from the browser catalog when returned by Get Browser Catalog.

Comment >>

Browser, Context & Page, line 1316

Switch Context

Switches the active BrowserContext to another open context.

Arguments

NameDefaultType
idrequiredstr
browser=CURRENTUnion

Returns

str

Tags

BrowserControlSetter

Documentation

Switches the active BrowserContext to another open context.

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

Arguments Description
id The id of the context to switch to. Example: context=525d8e5b-3c4e-4baa-bfd4-dfdbc6e86089. A context id is returned by New Context when it is started or can be fetched from the browser catalog when returned by Get Browser Catalog.
browser The browser in which to search for that context. CURRENT for the currently active browser, ALL to search in all open browsers or the id of the browser where to switch context.

Example:

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

Comment >>

Browser, Context & Page, line 1349

Switch Page

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

Arguments

NameDefaultType
idrequiredUnion
context=CURRENTUnion
browser=CURRENTUnion

Returns

str

Tags

BrowserControlSetter

Documentation

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

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

Arguments Description
id The id or alias of the page to switch to. Example: page=8baf2991-5eaf-444d-a318-8045f914e96a or NEW. Can be a string or a dictionary returned by New Page Keyword. A page id can be fetched from the browser catalog when returned by Get Browser Catalog. NEW can be used to switch to a pop-up that just has been opened by the webpage, CURRENT can be used to switch to the active page of a different context or browser, identified by their id.
context The context in which to search for that page. CURRENT for the currently active context, ALL to search in all open contexts or the id of the context where to switch page.
browser The browser in which to search for that page. CURRENT for the currently active browser, ALL to search in all open browsers or the id of the browser where to switch page.

If a page id is given, the context and browser arguments are ignored and the page is searched from all open browsers.

NEW may time out if no new page is opened before the library timeout expires.

Example:

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

Comment >>

Browser, Context & Page, line 1402

Take Screenshot

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

Arguments

NameDefaultType
filename=robotframework-browser-screenshot-{index}Union
selector=NoneUnion
cropnamed only=NoneUnion
disableAnimationsnamed only=Falsebool
fileTypenamed only=pngScreenshotFileTypes
fullPagenamed only=Falsebool
highlight_selectornamed only=NoneUnion
log_screenshotnamed only=Truebool
masknamed only=Union
maskColornamed only=NoneUnion
omitBackgroundnamed only=Falsebool
qualitynamed only=NoneUnion
scalenamed only=NoneUnion
return_asnamed only=path_stringScreenshotReturnType
timeoutnamed only=NoneUnion

Returns

Union

Tags

PageContent

Documentation

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

Arguments Description
filename Filename into which to save. The file will be saved into the Robot Framework ${OUTPUTDIR}/browser/screenshot directory by default, but it can be overwritten by providing a custom path or filename. String {index} in the filename will be replaced with a rolling number. Use this to not overwrite filenames. If filename equals to UUID (case insensitive), then the filename is created by Python uuid; https://docs.python.org/3/library/uuid.html. If filename equals to EMBED (case insensitive) or ${NONE}, then the screenshot is embedded as a Base64 image into the log.html. The image is saved temporarily to the disk and a warning is displayed if removing the temporary file fails. The ${OUTPUTDIR}/browser/screenshot directory 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 the current viewport.
crop Crops the taken screenshot to the given box. It takes the same dictionary as returned from Get BoundingBox. Cropping only works on a page screenshot, so when 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 the transitionend event. - infinite animations are cancelled to initial state, and then played over after the screenshot.
fileType png or jpeg. Specifies the screenshot type, defaults to png.
fullPage When True, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to False.
highlight_selector Highlights elements while taking the screenshot. Highlight method is playwright. This highlighting also automatically happens if the Robot Framework variable ${ROBOT_FRAMEWORK_BROWSER_FAILING_SELECTOR} is set to a selector string and is available on page. This is the case if highlight_on_failure has been set to True when importing Browser library.
log_screenshot When set to False the screenshot is taken but not logged into log.html.
mask Specify selectors that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box #FF00FF that completely covers their bounding box. The argument can take a single selector string or a list of selector strings if multiple different elements should be masked.
maskColor Specify the color of the overlay box for masked elements, in CSS color format. Default color is pink #FF00FF.
omitBackground Hides the default white background and allows capturing screenshots with transparency. Not applicable to jpeg images.
quality The quality of the image, between 0-100. Not applicable to png images.
scale css or device. css will reduce the image size and device keeps the image in its original size. Defaults to device.
return_as Defines what this keyword returns. Possible values are documented in ScreenshotReturnType. It can be either a path to the screenshot file as string or Path object, or the image data as bytes or base64 encoded string. When the screenshot is embedded into the log, path_string returns the string EMBED.
timeout Maximum time how long taking the screenshot can last, defaults to the library timeout. Supports Robot Framework time format, like 10s or 1 min, pass 0 to disable the timeout. The default value can be changed by using the Set Browser Timeout keyword.

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 filenameTake Screenshot   selector=id=username_field    # Captures element in image# Takes screenshot with jpeg extension, defines image quality and timeout how long taking screenshot should lastTake Screenshot   fullPage=True    fileType=jpeg    quality=50    timeout=10sTake Screenshot   EMBED                         # Screenshot is embedded as Base64 image to the log.html.Take Screenshot   UUID                          # Takes screenshot from page with filename generated by: https://docs.python.org/3/library/uuid.html.

Comment >>

Browser Control, line 137

Tap

Simulates tap on the element found by selector.

Arguments

NameDefaultType
selectorrequiredstr
*modifiersKeyboardModifier
forcenamed only=Falsebool
noWaitAfternamed only=Falsebool
position_xnamed only=NoneUnion
position_ynamed only=NoneUnion
trialnamed only=Falsebool

Tags

PageContentSetter

Documentation

Simulates tap on the element found by selector.

Requires that the hasTouch option of New Context is set to true. This method taps the element by performing the following steps:

  • Wait for actionability checks on the element, unless the force option is set.
  • Scroll the element into view if needed.
  • Use page.touchscreen to tap the center of the element, or the specified position.
  • Wait for initiated navigations to either succeed or fail.
Arguments Description
selector Selector element to tap. See the Finding elements section for details about the selectors.
*modifiers Modifier keys to press. Ensures that only these modifiers are pressed during the tap, 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 Alt, Control, ControlOrMeta, Meta and Shift.
force Whether to bypass the actionability checks. Defaults to False.
noWaitAfter Deprecated. This option has no effect. Defaults to False.
position_x position_y A point to tap relative to the top-left corner of element bounding-box. Only positive values within the bounding-box are allowed. Both values must be given, otherwise the position is ignored. If not specified, taps some visible point of the element.
trial When set, this method only performs the actionability checks and skips the action. Defaults to False.

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

Example:

New Context    hasTouch=${True}New Page    ${URL}Tap    css=input#login_button

Comment >>

Interaction, line 428

Type Secret

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

Arguments

NameDefaultType
selectorrequiredstr
secretrequiredUnion
delay=0:00:00timedelta
clear=Truebool

Tags

PageContentSetter

Documentation

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

Arguments Description
selector Selector of the text field. See the Finding elements section for details about the selectors.
secret Supports Robot Framework 7.4 Secret type as normal variable (with curly braces). Also environment variable name with % prefix or a local variable with $ prefix that has the secret text value (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 should not be cleared before typing. Defaults to True.

This keyword does not log the secret in Robot Framework logs, but if Playwright debug logs are enabled, the secret will be visible as plain text in the Playwright debug logs, regardless of the Robot Framework log level or how secret is resolved.

This keyword supports Robot Framework 7.4 Secret variable type, which is the recommended way if you are using Robot Framework 7.4 or newer.

For older Robot Framework versions the keyword supports resolving secrets from environment variables and Robot Framework variables in the following ways. The keyword resolves the secret from a Robot Framework variable internally, when the secret variable is prefixed with $, without the curly braces. Example: $Password will resolve to the ${Password} Robot Framework variable.

If the secret variable is prefixed with %, the library will resolve the corresponding environment variable. Example: %ENV_PWD will resolve to the %{ENV_PWD} environment variable.

Using normal Robot Framework variables like ${password}, which are not Secret type variables, will not work!

Normal plain text will not work. If you want to use plain text, use the Type Text keyword instead.

This keyword also works with a cryptographic cipher text that has been encrypted by CryptoLibrary. See CryptoLibrary for more details.

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 Secret type variableType Secret    input#username_field    $username      # Keyword resolves ${username} variable value from Robot Framework variablesType Secret    input#username_field    %username      # Keyword resolves $USERNAME/%USERNAME% variable value from environment variables

Comment >>

Interaction, line 137

Type Text

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

Arguments

NameDefaultType
selectorrequiredstr
txtrequiredstr
delay=0:00:00timedelta
clear=Truebool

Tags

PageContentSetter

Documentation

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

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

Arguments Description
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 should 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 filling the full text at once.

Example

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

Comment >>

Interaction, line 51

Uncheck Checkbox

Unchecks the checkbox found by selector.

Arguments

NameDefaultType
selectorrequiredstr
force=Falsebool

Tags

PageContentSetter

Documentation

Unchecks the checkbox found by selector.

Arguments Description
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 >>

Interaction, line 716

Upload File By Selector

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

Arguments

NameDefaultType
selectorrequiredstr
pathrequiredUnion
*extra_pathsPathLike

Tags

PageContentSetter

Documentation

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

Fails if the upload is not done before the library timeout. Therefore it may be necessary to increase the timeout with Set Browser Timeout. It is possible to upload multiple files or folders by defining additional files or folders in extra_paths.

If a path is a directory, all files from the directory are uploaded. Subdirectories are not included. It is possible to upload files and directories with the same keyword. The keyword fails if a given path does not exist.

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

Arguments Description
selector Identifies the file input element.
path Path to the file or folder to be uploaded. Can also be a FileUploadBuffer dictionary.
extra_paths Additional paths to files or folders to be uploaded.

If path is a FileUploadBuffer dictionary, then the structure should be:

{  'name': str,  'mimeType': str,  'buffer': str}

If path argument is FileUploadBuffer, then extra_paths argument is not supported and using it will raise an error.

Upload single file example:

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

Upload many files example:

Upload File By Selector    //input[@type='file']    file1.zip    file2.zip    file3.zip

Upload folder example:

Upload File By Selector    //input[@type='file']    /path/to/folder

Upload as buffer example:

${text} =    Get File    /path/to/file    # Read file from diskVAR    &{buffer}    name=not_here.txt    mimeType=text/plain    buffer=${text}    # Create buffer dictionaryUpload File By Selector    id=file_chooser    ${buffer}    # Upload buffer

Comment >>

Interaction, line 1408

Wait For

Waits for promises to finish and returns results from them.

Arguments

NameDefaultType
*promisesFuture

Tags

Wait

Documentation

Waits for promises to finish and returns results from them.

Returns a single result if only one promise is waited for. Otherwise it returns a list of results in the same order as the promises were given. If one of the promises fails, then this keyword will fail.

See Promise To for more information about promises.

For general waiting of elements please see Implicit waiting.

Arguments Description
promises Promises to wait for.

Example:

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

Comment >>

Promises, line 237

Wait For Alert

Returns a promise to wait for next dialog on page, handles it with action and optionally verifies the dialogs text.

Arguments

NameDefaultType
actionrequiredDialogAction
prompt_input=str
text=NoneUnion
timeout=NoneUnion

Tags

PageContentWait

Documentation

Returns a promise to wait for next dialog on page, handles it with action and optionally verifies the dialogs text.

Dialog/alert can be any of alert, beforeunload, confirm or prompt.

Arguments Description
action How to handle the alert. Can be accept or dismiss.
prompt_input The value to enter into the prompt. Only valid if the action argument equals accept. Defaults to an empty string.
text Optional text to verify the dialog text with.
timeout Optional timeout in Robot Framework time format. Defaults to the library timeout.

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

Example with returning text:

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

Example with text verification:

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

Comment >>

Interaction, line 912

Wait For Alerts

Returns a promise to wait for multiple dialogs on a page.

Arguments

NameDefaultType
actionsrequiredlist
prompt_inputsrequiredlist
textsrequiredlist
timeout=NoneUnion

Returns

list

Tags

PageContentWait

Documentation

Returns a promise to wait for multiple dialogs on a page.

Handles each alert/dialog with actions and optionally verifies the dialog texts. Dialog/alert can be any of alert, beforeunload, confirm or prompt.

Arguments Description
actions List of how to handle the alerts. Can be accept or dismiss.
prompt_inputs List of the values to enter into the prompts. Only valid if the corresponding action equals accept. Use None if no input is needed.
texts List of optional texts to verify the dialog texts with. Use None if text verification should be disabled.
timeout Optional timeout in Robot Framework time format. Defaults to the library timeout. The timeout is applied to each alert separately.

There must be an equal amount of items in the actions, prompt_inputs and texts lists. Use None if texts and/or prompt inputs are not needed.

This keyword works in the same way as Wait For Alert, but it can handle multiple alerts with one promise. Like the Wait For Alert keyword, this keyword must be called as an argument to the Promise To keyword.

Example to handle two alerts, first one is accepted and second one is dismissed:

${promise} =    Promise To...    Wait For Alerts...    ["accept", "dismiss"]...    [None, None]...    [None, None]Click    id=alerts${texts} =    Wait For    ${promise}

Example to handle confirm and prompt alert. Example assumes that the first is a confirm and second one is prompt:

${promise} =    Promise To...    Wait For Alerts...    ["dismiss", "accept"]...    [None, "I am a prompt"]...    ["First alert accepted?", None]Click    id=confirmAndPrompt${texts} =    Wait For    ${promise}

Comment >>

Interaction, line 962

Wait For All Promises

Waits for all promises to finish.

Takes no arguments.

Tags

Wait

Documentation

Waits for all promises to finish.

Waits for all promises which have been created but not yet waited for with Wait For. If one of the promises fails, then this keyword will fail.

Example:

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

Comment >>

Promises, line 264

Wait For Condition

Waits for a condition, defined with Browser getter keywords, to become True.

Arguments

NameDefaultType
conditionrequiredConditionInputs
*argsAny
timeoutnamed only=NoneUnion
messagenamed only=NoneUnion

Returns

Any

Tags

PageContentWait

Documentation

Waits for a condition, defined with Browser getter keywords, to become True.

This keyword is basically just a wrapper around our assertion keywords, but with a timeout. It can be used to wait for anything that also can be asserted with our keywords.

In comparison to Robot Framework's Wait Until Keyword Succeeds this keyword is more readable and easier to use, but is limited to Browser library's assertion keywords.

Arguments Description
condition A condition, defined with Browser getter keywords, without the word Get.
*args Arguments to pass to the condition keyword.
timeout Timeout to wait for the condition to become True. Uses default timeout of the library if not set. As the other assertion keywords this timeout only influences the time the assertion is retried. The browser timeout is used to wait for the element to be found.
message Overrides the default error message.

The easiest way to use this keyword is first starting with an assertion keyword with assertion like: Get Text

Start:

Get Text    id=status_bar   contains    Done

Then you replace the word Get with Wait For Condition and if necessary add the timeout argument.

End:

Wait For Condition    Text    id=status_bar   contains    Done

Example usage:

Wait For Condition    Element States    id=cdk-overlay-0    ==    detachedWait For Condition    Element States     //h1    contains    visible    editable    enabled    timeout=2 sWait For Condition    Title    should start with    RobotWait For Condition    Url    should end with    robotframework.org

Comment >>

Waiting, line 243

Wait For Elements State

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

Arguments

NameDefaultType
selectorrequiredstr
state=visibleElementState
timeout=NoneUnion
message=NoneUnion

Tags

PageContentWait

Documentation

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

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

If users experience reliability issues with this keyword, consider using Wait for Condition with Get Element States keyword instead. Wait For Elements State uses features of Playwright to wait for element states. However, in some situations these features might not work as expected. Wait for Condition with Get Element States is more robust as it uses Browser library's own waiting mechanisms that actively poll the state of an element.

State options are appearing in or disappearing from the DOM, becoming visible or hidden, and the other states listed in ElementState. 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.

Arguments Description
selector Selector of the corresponding object. See the Finding elements section for details about the selectors.
state See ElementState for explanation.
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 the state argument value for the states which are waited for by Playwright, that are attached, detached, visible, hidden, stable, enabled, disabled and editable. For all other states, it is the JavaScript expression which is evaluated for the element.

The states focused and defocused are not supported with iframe selectors, which contain >>>. In that case the keyword raises an error and suggests to use Wait For Condition with Get Element States instead.

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

Example:

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

Comment >>

Waiting, line 39

Wait For Function

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

Arguments

NameDefaultType
functionrequiredstr
selector=str
polling=rafUnion
timeout=NoneUnion
message=NoneUnion

Tags

PageContentWait

Documentation

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

Arguments Description
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 a selector is given, function must be a function with an argument which receives the element handle. 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 the interval between polls.
timeout Uses default timeout of the library 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=4sClick         \#progress_barWait For      ${promise}

Comment >>

Waiting, line 167

Wait For Load State

Waits until the page reaches the required load state.

Arguments

NameDefaultType
state=loadPageLoadStates
timeout=NoneUnion

Tags

PageContentWait

Documentation

Waits until the page reaches the required load state.

This resolves when the page reaches a required load state, load by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.

Arguments Description
state State to wait for, defaults to load. Possible values are load, domcontentloaded, networkidle and commit.
timeout Timeout supports Robot Framework time format. Uses browser timeout if not set.

If the state has been already reached while loading current document, the underlying Playwright will resolve immediately. Can be one of:

load - wait for the load event to be fired.domcontentloaded - wait for the DOMContentLoaded event to be fired.networkidle - DISCOURAGED wait until there are no network connections for at least 500 ms.commit - not supported by this keyword, the keyword returns immediately without waiting.

Example:

Go To                         ${URL}Wait For Load State    domcontentloaded    timeout=3s

Waiting, line 312

Wait For Navigation

Waits until the page has navigated to the given url.

Arguments

NameDefaultType
urlrequiredUnion
timeout=NoneUnion
wait_until=loadPageLoadStates

Tags

HTTPWait

Documentation

Waits until the page has navigated to the given url.

Arguments Description
url Expected navigation target address, either a Glob-Pattern (a plain string without wildcards matches exactly) or a JavaScript-like regex wrapped in / symbols.
timeout Timeout supports Robot Framework time format. Uses default timeout if not set.
wait_until When to consider the 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.

The keyword works only when the page is loaded and it does not work if only the 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 the keyword will fail.

Example:

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

Comment >>

Network, line 276

Wait For Request

Waits for a request matching matcher to be made.

Arguments

NameDefaultType
matcher=Union
timeout=NoneUnion

Returns

Union

Tags

HTTPWait

Documentation

Waits for a request matching matcher to be made.

Only the request is awaited, not its response. See Wait For Response if the response is needed.

The returned object is a dictionary with the keys url, method, headers and postData. headers is a dictionary of request headers. postData is None if the request has no body, a dictionary if the body is valid JSON and otherwise the body as a string.

Arguments Description
matcher Request URL matcher. Can be a string (Glob-Pattern), a JavaScript RegExp (enclosed in / with optional trailing flags) or a JavaScript arrow-function that receives the Request object and returns a boolean. By default (with an empty string) the first request is matched. For additional information, see the Playwright waitForRequest documentation.
timeout Timeout supports Robot Framework time format. Uses default timeout if not set.

See Wait For Response for more details about the matcher.

CAUTION: Before Browser library 17.0.0, the matcher argument was always either a regex or JS function. But the regex did not need to be in slashes. The most simple way to migrate to the new syntax is to add slashes around the matcher. So /api/get/json becomes //api/get/json/.

Comment >>

Network, line 154

Wait For Response

Waits for a response matching matcher and returns the response as a Robot Framework dictionary.

Arguments

NameDefaultType
matcher=Union
timeout=NoneUnion

Returns

Union

Tags

HTTPWait

Documentation

Waits for a response matching matcher and returns the response as a Robot Framework dictionary.

The keyword waits until the response headers are received and then reads the response body.

The response, which is returned by this keyword, is a Robot Framework dictionary with the following attributes:

  • status <int> The status code of the response.
  • statusText <str> Status text corresponding to status, e.g. OK or INTERNAL SERVER ERROR. This may not be available for all browsers.
  • body <dict | str> The response body. If the body can be parsed as a JSON object, it will be returned as Python dictionary, otherwise it is returned as a string. It is None if the body could not be read and the key is missing altogether if the response body is empty.
  • headers <dict> A dictionary containing all response headers.
  • ok <bool> Whether the request was successful, i.e. the status is in the range 200-299.
  • request <dict> containing method <str>, headers <dict> and postData <dict> | <str>
  • url <str> url of the response.
Arguments Description
matcher Response URL matcher. Can be a string (Glob-Pattern), a JavaScript RegExp (enclosed in / with optional trailing flags) or a JavaScript arrow-function that receives the Response object and returns a boolean. By default (with an empty string) the first response is matched. For additional information, see the Playwright page.waitForResponse documentation.
timeout Timeout supports Robot Framework time format. Uses default timeout if not set.

CAUTION: Before Browser library 17.0.0, the matcher argument was always either a regex or JS function. But the regex did not need to be in slashes. The most simple way to migrate to the new syntax is to add slashes around the matcher. So /api/get/json becomes //api/get/json/.

Matcher Examples:

Glob-Pattern:

Glob-Patterns are strings that can contain wildcards. Possible wildcards/patterns are:

  • * matches any number of characters, except /
  • ** matches any number of characters, including /
  • ? matches one character, except /
  • [abc] matches one character in the brackets (in this example a, b or c)
  • [a-z] matches one character in the range (in this example a to z)
  • {foo,bar,baz} matches one of the strings in the braces (in this example foo, bar or baz)

Example:

Wait For Response    **/api/get/text    # matches any response with url ending with /api/get/text. example: https://browser.fi/api/get/text

RegExp:

Regular Expressions are JavaScript regular expressions enclosed in / with optional trailing flags. Be aware that backslashes need to be escaped in Robot Framework, e.g. \\w instead of \w. See regex101 for more information on Regular Expressions.

Example:

Wait For Response    /http://\\w+:\\d+/api/get/text/i    # matches any response with url ending with /api/get/text and containing http:// followed by any word and port. example: http://localhost:8080/api/get/text

JavaScript Arrow-Function:

JavaScript Arrow-Functions are anonymous JavaScript functions that receive the Response object and return a boolean.

Example:

Wait For Response    response => response.url() === 'http://localhost/api/post' && response.status() === 200    # matches any response with url http://localhost/api/post and status code 200

Robot Examples:

Synchronous Example:

Click                \#delayed_request    # Creates response which should be waited before next actionsWait For Response    matcher=/http://\\w+:\\d+/api/get/text/iClick                \#save

Asynchronous Example:

${promise} =    Promise To    Wait For Response    timeout=60sClick           \#delayed_request    # Creates response which should be waited before pressing save.Click           \#nextWait For        ${promise}            # Waits for the responseClick           \#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 >>

Network, line 187

Data types 83

AreaFieldsEnum

One of a fixed set of values, written as a plain string.

Enumeration that defines which coordinates of an area should be selected.

ALL defines that all fields are selected and a dictionary with all information is returned.

Accepted values

topleftbottomrightALL

AriaSnapshotModeEnum

One of a fixed set of values, written as a plain string.

Defines the mode of the AriaSnapshot.

Value Description
default Standard aria snapshot.
ai Snapshot optimized for AI consumption. It includes element references like [ref=e2], includes snapshots of iframes inside the target and does not wait for a matching element, but fails immediately when no element matches.

Accepted values

defaultai

AriaSnapshotReturnTypeEnum

One of a fixed set of values, written as a plain string.

Defines the return type of the AriaSnapshot.

Value Description
dict returns the snapshot as a dictionary.
yaml returns the snapshot as a yaml string.
parsed returns the snapshot as a tree of node dictionaries.

dict loads the yaml as it is. Role, name and all annotations of an element stay inside the dictionary keys, for example {'heading "Login Page" [level=1]': None}.

parsed splits that information into separate keys. Every node has role, name, text, props and children, and its values are reachable both as ${node}[role] and as ${node.role}. Annotations without a value, like [selected], become True, [level=2] becomes an integer and box uses the same keys as Get BoundingBox. The /url entry of a link is an annotation in Playwright, not an element, and therefore becomes the url property of the link instead of one of its children.

Examples

All outputs below come from the same element of the same page. It offers fourteen tag options; the examples stop after the fourth one:

New Browser    chromiumNew Page       https://robotframework-browser.org/keywords${snapshot} =    Get Aria Snapshot    .rail-top

return_type=yaml (default)

- text: Filter keywords- searchbox "Filter keywords"- group: Version 20.3.0- text: Filter by tag- combobox "Filter by tag":  - option "— Show all tags —" [selected]  - option "Setter (84)"  - option "PageContent (83)"  - option "Getter (45)"

return_type=yaml with boxes=True

- text: Filter keywords- searchbox "Filter keywords" [box=12,77,279,30]- group [box=12,116,279,34]: Version 20.3.0- text: Filter by tag- combobox "Filter by tag" [box=12,158,279,32]:  - option "— Show all tags —" [selected] [box=0,0,0,0]  - option "Setter (84)" [box=0,0,0,0]  - option "PageContent (83)" [box=0,0,0,0]  - option "Getter (45)" [box=0,0,0,0]

return_type=yaml with boxes=True and mode=ai

- generic [ref=f2e1] [box=0,65,303,137]:  - generic [ref=f2e3] [box=12,77,279,30]:    - generic [ref=f2e4] [box=12,77,1,1]: Filter keywords    - searchbox "Filter keywords" [ref=f2e5] [box=12,77,279,30]  - generic [ref=f2e6] [box=12,116,279,74]:    - group [ref=f2e7] [box=12,116,279,34]:      - generic "Version 20.3.0" [ref=f2e8] [cursor=pointer] [box=12,116,157,34]:        - generic [ref=f2e9] [box=22,124,66,18]: Version        - generic [ref=f2e10] [box=96,121,49,22]: 20.3.0    - generic [ref=f2e12] [box=12,158,279,32]:      - generic [ref=f2e13] [box=12,158,1,1]: Filter by tag      - combobox "Filter by tag" [ref=f2e14] [box=12,158,279,32]:        - option "— Show all tags —" [selected] [box=0,0,0,0]        - option "Setter (84)" [box=0,0,0,0]        - option "PageContent (83)" [box=0,0,0,0]        - option "Getter (45)" [box=0,0,0,0]

return_type=dict with boxes=True

[  {    'text': 'Filter keywords'  },  'searchbox "Filter keywords" [box=12,77,279,30]',  {    'group [box=12,116,279,34]': 'Version 20.3.0'  },  {    'text': 'Filter by tag'  },  {    'combobox "Filter by tag" [box=12,158,279,32]': [      'option "— Show all tags —" [selected] [box=0,0,0,0]',      'option "Setter (84)" [box=0,0,0,0]',      'option "PageContent (83)" [box=0,0,0,0]'      'option "Getter (45)" [box=0,0,0,0]'    ]  }]

return_type=parsed with boxes=True

Fully parsed snapshot as Robot Framework dictionary:

[  {    'role': 'text',    'name': None,    'text': 'Filter keywords',    'props': {},    'children': []  },  {    'role': 'searchbox',    'name': 'Filter keywords',    'text': None,    'props': {      'box': {        'x': 12,        'y': 77,        'width': 279,        'height': 30      }    },    'children': []  },  {    'role': 'group',    'name': None,    'text': 'Version 20.3.0',    'props': {      'box': {        'x': 12,        'y': 116,        'width': 279,        'height': 34      }    },    'children': []  },  {    'role': 'text',    'name': None,    'text': 'Filter by tag',    'props': {},    'children': []  },  {    'role': 'combobox',    'name': 'Filter by tag',    'text': None,    'props': {      'box': {        'x': 12,        'y': 158,        'width': 279,        'height': 32      }    },    'children': [      {        'role': 'option',        'name': '— Show all tags —',        'text': None,        'props': {          'selected': True,          'box': {            'x': 0,            'y': 0,            'width': 0,            'height': 0          }        },        'children': []      },      {        'role': 'option',        'name': 'Setter (84)',        'text': None,        'props': {          'box': {            'x': 0,            'y': 0,            'width': 0,            'height': 0          }        },        'children': []      },      {        'role': 'option',        'name': 'PageContent (83)',        'text': None,        'props': {          'box': {            'x': 0,            'y': 0,            'width': 0,            'height': 0          }        },        'children': []      },      {        'role': 'option',        'name': 'Getter (45)',        'text': None,        'props': {          'box': {            'x': 0,            'y': 0,            'width': 0,            'height': 0          }        },        'children': []      }    ]  }]

Accepted values

dictyamlparsed

AssertionOperatorEnum

One of a fixed set of values, written as a plain string.

Currently supported assertion operators are:

Operator Alternative Operators Description Validate Equivalent
== equal, equals, should be Checks if returned value is equal to expected value. value == expected
!= inequal, should not be Checks if returned value is not equal to expected value. value != expected
> greater than Checks if returned value is greater than expected value. value > expected
>= Checks if returned value is greater than or equal to expected value. value >= expected
< less than Checks if returned value is less than expected value. value < expected
<= Checks if returned value is less than or equal to expected value. value <= expected
*= contains Checks if returned value contains expected value as substring. expected in value
not contains Checks if returned value does not contain expected value as substring. expected in value
^= should start with, starts Checks if returned value starts with expected value. re.search(f"^{expected}", value)
$= should end with, ends Checks if returned value ends with expected value. re.search(f"{expected}$", value)
matches Checks if given RegEx matches minimum once in returned value. re.search(expected, value)
validate Checks if given Python expression evaluates to True.
evaluate then When using this operator, the keyword does return the evaluated Python expression.

There are three different possibilities what keyword returns when matches operator is used: string, tuple or dictionary. What keyword returns depends on how the RegEx is formed. If RegEx does not contain group(s), then keyword will return the string without modifications. If RegEx contains groups, meaning (...), then keyword will return a tuple. Each tuple item contains the text which is matched by the group. If there is group and group has a name, (?P<name>...) syntax, then keyword returns a dictionary. In this case dictionary key is the group name and value contains the matched text. If there mix of groups and groups with names, then tuple is returned.

Currently supported formatters for assertions are:

Formatter Description
normalize spaces Substitutes multiple spaces to single space from the value
strip Removes spaces from the beginning and end of the value
case insensitive Converts value to lower case before comparing
apply to expected Applies rules also for the expected value

Formatters are applied to the value before assertion is performed and keywords returns a value where rule is applied. Formatter is only applied to the value which keyword returns and not all rules are valid for all assertion operators. If apply to expected formatter is defined, then formatters are then formatter are also applied to expected value.

Accepted values

equalequals==should beinequal!=should not beless than<greater than><=>=containsnot contains*=starts^=should start withendsshould end with$=matchesvalidatethenevaluate

AutoClosingLevelEnum

One of a fixed set of values, written as a plain string.

Controls when contexts and pages are closed during the test execution.

If automatic closing level is TEST, contexts and pages that are created during a single test are automatically closed when the test ends. Contexts and pages that are created during suite setup are closed when the suite teardown ends.

If automatic closing level is SUITE, all contexts and pages that are created during the test suite are closed when the suite teardown ends.

If automatic closing level is MANUAL, nothing is closed automatically while the test execution is ongoing. All browsers, context and pages are automatically closed when test execution ends.

If automatic closing level is KEEP, nothing is closed automatically while the test execution is ongoing. Also, nothing is closed when test execution ends, including the node process. Therefore, it is users responsibility to close all browsers, context and pages and ensure that all process that are left running after the test execution end are closed. This level is only intended for test case development and must not be used when running tests in CI or similar environments.

Automatic closing can be configured or switched off with the auto_closing_level library import parameter.

See: Importing

Accepted values

SUITETESTMANUALKEEP

booleanStandard

Converted by Robot Framework itself.

Strings TRUE, YES, ON, 1 and possible localization specific "true strings" are converted to Boolean True, the empty string, strings FALSE, NO, OFF and 0 and possibly localization specific "false strings" are converted to Boolean False, and the string NONE is converted to the Python None object. Other strings and all other values are passed as-is, allowing keywords to handle them specially if needed. All string comparisons are case-insensitive.

Examples: TRUE (converted to True), off (converted to False), example (used as-is)

BoundingBoxTypedDict

A dictionary with known keys.

Bounding box of an element.

Key Description
x The amount of pixel between the left border of the page and the left border of the element.
y The amount of pixel between the top border of the page and the top border of the element.
width The width of the element, excluding margins.
height The height of the element, excluding margins.

Keys

KeyRequiredType
xnofloat
ynofloat
widthnofloat
heightnofloat

BoundingBoxFieldsEnum

One of a fixed set of values, written as a plain string.

Enumeration that defines which location information of an element should be selected.

x / y defines the position of the top left corner of an element.

width / height defines the size of an elements bounding box.

ALL defines that all fields are selected and a dictionary with all information is returned.

Accepted values

widthheightxyALL

BrowserInfoTypedDict

A dictionary with known keys.

Dictionary that contains information about a browser instance.

Key Description
type The browser type. e.g. chromium, firefox or webkit.
id The unique id of the browser instance.
contexts List of context information opened by the browser.
activeContext The id of the active context.
activeBrowser Boolean if the browser is the currently active browser.

Structure:

{  'type': str,  'id': str,  'contexts': [      {          'type': str,          'id': str,          'activePage': str,          'pages': [              {                  'type': str,                  'title': str,                  'url': str,                  'id': str,                  'timestamp': float              },              ...          ]      },      ...  ],  'activeContext': str,  'activeBrowser': bool}

Keys

KeyRequiredType
typeyesstr
idyesstr
contextsyeslist[Browser.utils.data_types.ContextInfo]
activeContextyesstr
activeBrowseryesbool

bytesStandard

Converted by Robot Framework itself.

Strings are converted to bytes so that each Unicode code point below 256 is directly mapped to a matching byte. Higher code points are not allowed. Robot Framework's \xHH escape syntax is convenient with bytes having non-printable values.

Examples: good, hyvä (same as hyv\xE4), \x00 (the null byte)

Integers and sequences of integers are converted to matching bytes directly. They must be in range 0-255.

Examples: 0 (converted to the null byte), [82, 70] (converted to RF)

Support for integers and sequences of integers is new in Robot Framework 7.4.

ClientCertificateTypedDict

A dictionary with known keys.

Defines client certificate.

  • origin Exact origin that the certificate is valid for. Origin includes https protocol, a hostname and optionally a port.
  • certPath Optional Path to the file with the certificate in PEM format.
  • keyPath Optional Path to the file with the private key in PEM format.
  • pfxPath Optional Path to the PFX or PKCS12 encoded private key and certificate chain.
  • passphrase Optional Passphrase for the private key (PEM or PFX).

Example usage: {'origin': 'https://playwright.dev', 'pfxPath': 'certificate.p12', 'passphrase': 'secret'}

Keys

KeyRequiredType
originnostr
certPathnostr
keyPathnostr
pfxPathnostr
passphrasenostr

ClientCredentialTypedDict

A dictionary with known keys.

Returned client credential.

  • id Base64url-encoded credential id.
  • rpId Relying party id (typically the site's effective domain).
  • userHandle Base64url-encoded user handle.
  • privateKey Base64url-encoded PKCS#8 (DER) private key.
  • publicKey Base64url-encoded SPKI (DER) public key.

Example usage: {'id': 'localhost', 'rpId': 'localhost', 'userHandle': 'localhost', 'privateKey': 'localhost', 'publicKey': 'localhost'}

Keys

KeyRequiredType
idyesstr
rpIdyesstr
userHandleyesstr
privateKeyyesSecret
publicKeyyesSecret

CLockAdvanceTypeEnum

One of a fixed set of values, written as a plain string.

Defines how time is advanced.

fast_forward: Advance the clock by jumping forward in time. run_for: Advance the clock, firing all the time-related callbacks.

fast_forward will Only fires due timers at most once. This is equivalent to user closing the laptop lid for a while and reopening it later, after given time.

Accepted values

fast_forwardrun_for

ClockTypeEnum

One of a fixed set of values, written as a plain string.

Defines how time is set.

The recommended approach is to use fixed to set the time to a specific value.

fixed: Sets the fixed time for Date.now() and new Date(). system: Is only recommended for advanced use cases. install: initializes the clock and allows you to: pause_at: Pauses the time at a specific time. fast_forward: Fast forwards the time. run_for: Runs the time for a specific duration. resume: Resumes the time.

Accepted values

fixedsysteminstall

Used by

Set Time

ColorSchemeEnum

One of a fixed set of values, written as a plain string.

Emulates 'prefers-color-scheme' media feature. Supported values are 'light', 'dark', 'no-preference' and null. Passing null disables color scheme emulation. no-preference is deprecated.

See emulateMedia(options) for more details.

Accepted values

darklightno-preferencenull

ConditionInputsEnum

One of a fixed set of values, written as a plain string.

Following values are allowed and represent the assertion keywords to use:

Value Keyword
Attribute Get Attribute
Attribute Names Get Attribute Names
BoundingBox Get BoundingBox
Browser Catalog Get Browser Catalog
Checkbox State Get Checkbox State
Classes Get Classes
Client Size Get Client Size
Download State Get Download State
Element Count Get Element Count
Element States Get Element States
Page Source Get Page Source
Property Get Property
Scroll Position Get Scroll Position
Scroll Size Get Scroll Size
Select Options Get Select Options
Selected Options Get Selected Options
Style Get Style
Table Cell Index Get Table Cell Index
Table Row Index Get Table Row Index
Text Get Text
Title Get Title
Url Get Url
Viewport Size Get Viewport Size

Accepted values

attributeattribute_namesbounding_boxbrowser_catalogcheckbox_stateclassesclient_sizedownload_stateelement_countelement_statespage_sourcepropertyscroll_positionscroll_sizeselect_optionsselected_optionsstyletable_cell_indextable_row_indextexttitleurlviewport_size

CookieSameSiteEnum

One of a fixed set of values, written as a plain string.

Enum that defines the Cookie SameSite type.

It controls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks (CSRF).

The possible attribute values are:

Value Description
Strict Means that the browser sends the cookie only for same-site requests, that is, requests originating from the same site that set the cookie. If a request originates from a different domain or scheme (even with the same domain), no cookies with the SameSite=Strict attribute are sent.
Lax Means that the cookie is not sent on cross-site requests, such as on requests to load images or frames, but is sent when a user is navigating to the origin site from an external site (for example, when following a link). This is the default behavior if the SameSite attribute is not specified.
None means that the browser sends the cookie with both cross-site and same-site requests. The Secure attribute must also be set when setting this value.

See MDN Set-Cookie for more information.

Accepted values

StrictLaxNone

CookieTypeEnum

One of a fixed set of values, written as a plain string.

Enum that defines the Cookie type.

Accepted values

dictionarydictstringstr

CoverageTypeEnum

One of a fixed set of values, written as a plain string.

Enum that defines the type of coverage to collect.

js: JavaScript coverage. css: CSS coverage. all: Both CSS and JS coverage.

Accepted values

jscssall

datetimeStandard

Converted by Robot Framework itself.

String timestamps are expected to be in ISO 8601 like format YYYY-MM-DD hh:mm:ss.mmmmmm, where any non-digit character can be used as a separator or separators can be omitted altogether. Additionally, only the date part is mandatory, all possibly missing time components are considered to be zeros.

A special values NOW and TODAY (case-insensitive) can be used to get the current local datetime. This is new in Robot Framework 7.3.

Integers and floats are considered to represent seconds since the Unix epoch.

Examples: 2022-02-09T16:39:43.632269, 20220209 16:39, now, ${1644417583.632269} (Epoch time)

dictionaryStandard

Converted by Robot Framework itself.

Strings must be Python dictionary literals. They are converted to actual dictionaries using the ast.literal_eval function. They can contain any values ast.literal_eval supports, including dictionaries and other collections.

Any mapping is accepted and converted to a dict.

If the type has nested types like dict[str, int], items are converted to those types automatically. This in new in Robot Framework 6.0.

Examples: {'a': 1, 'b': 2}, {'key': 1, 'nested': {'key': 2}}

DimensionsTypedDict

A dictionary with known keys.

Dimensions of an object in pixels.

Keys

KeyRequiredType
widthyesint
heightyesint

DownloadInfoTypedDict

A dictionary with known keys.

Downloaded file information.

Key Description
saveAs is the path where downloaded file is saved. empty string if the file is not yet fully downloaded.
suggestedFilename is the suggested filename that was computed from the Content-Disposition response header.
state is the state of the download. i.e. in_progress, finished or canceled.
downloadID is the unique id of the download.

Keys

KeyRequiredType
saveAsyesstr
suggestedFilenameyesstr
stateyesstr
downloadIDyesstr | None

ElementRoleEnum

One of a fixed set of values, written as a plain string.

Role selector does not replace accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.

Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines do not recommend duplicating implicit roles and attributes by setting role and/or aria-* attributes to default values.

Accepted values

ALERTALERTDIALOGAPPLICATIONARTICLEBANNERBLOCKQUOTEBUTTONCAPTIONCELLCHECKBOXCODECOLUMNHEADERCOMBOBOXCOMPLEMENTARYCONTENTINFODEFINITIONDELETIONDIALOGDIRECTORYDOCUMENTEMPHASISFEEDFIGUREFORMGENERICGRIDGRIDCELLGROUPHEADINGIMGINSERTIONLINKLISTLISTBOXLISTITEMLOGMAINMARQUEEMATHMETERMENUMENUBARMENUITEMMENUITEMCHECKBOXMENUITEMRADIONAVIGATIONNONENOTEOPTIONPARAGRAPHPRESENTATIONPROGRESSBARRADIORADIOGROUPREGIONROWROWGROUPROWHEADERSCROLLBARSEARCHSEARCHBOXSEPARATORSLIDERSPINBUTTONSTATUSSTRONGSUBSCRIPTSUPERSCRIPTSWITCHTABTABLETABLISTTABPANELTERMTEXTBOXTIMETIMERTOOLBARTOOLTIPTREETREEGRIDTREEITEM

ElementStateEnum

One of a fixed set of values, written as a plain string.

Enum that defines the state an element can have.

The following states are possible:

State Description
attached to be present in DOM.
detached to not be present in DOM.
visible to have non or empty bounding box and no visibility:hidden.
hidden to be detached from DOM, or have an empty bounding box or visibility:hidden.
enabled to not be disabled.
disabled to be disabled. Can be used on <button>, <fieldset>, <input>, <optgroup>, <option>, <select> and <textarea>.
editable to not be readOnly.
readonly to be readOnly. Can be used on <input> and <textarea>.
selected to be selected. Can be used on <option>.
deselected to not be selected.
focused to be the activeElement.
defocused to not be the activeElement.
checked to be checked. Can be used on <input>.
unchecked to not be checked.
stable to be both visible and stable.

Accepted values

attacheddetachedvisiblehiddenenableddisablededitablereadonlyselecteddeselectedfocuseddefocusedcheckeduncheckedstable

FileUploadBufferTypedDict

A dictionary with known keys.

Dictionary that contains information about a file upload buffer.

Key Description
name The name of the file.
mimeType The mime type of the file.
buffer The file content.

Structure:

{  'name': str,  'mimeType': str,  'buffer': str}

Keys

KeyRequiredType
nameyesstr
mimeTypeyesstr
bufferyesstr

ForcedColorsEnum

One of a fixed set of values, written as a plain string.

Emulates 'forced-colors' media feature.

Supported values are 'active', 'none' and null. Passing null disables forced colors emulation.

Accepted values

activenonenull

FormatingRulesEnum

One of a fixed set of values, written as a plain string.

Enum that defines the available formatters.

Formatter Description
normalize spaces Replaces all kind of spaces with a single space.
strip Removes spaces from start and end of the string.
apply to expected Applies the formatter also to the expected value.
case insensitive Converts the string to lower case.

Accepted values

normalize spacesstripapply to expectedcase insensitive

FormatterKeywordsEnum

One of a fixed set of values, written as a plain string.

Enum that defines the available keywords for formatters.

Keywords that are not listed here, do not support formatters.

Accepted values

Get AttributeGet Browser CatalogGet Page SourceGet PropertyGet Select OptionsGet StyleGet TextGet TitleGet UrlLocalStorage Get ItemSessionStorage Get Item

GeoLocationTypedDict

A dictionary with known keys.

Defines the geolocation.

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

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

Keys

KeyRequiredType
longitudeyesfloat
latitudeyesfloat
accuracynofloat

HighLightElementTypedDict

A dictionary with known keys.

Presenter mode configuration options.

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, default is blue. Valid colors i.e. are: red, blue, yellow, pink, black

Keys

KeyRequiredType
durationnotimedelta
widthnostr
stylenostr
colornostr

HighlightModeEnum

One of a fixed set of values, written as a plain string.

Highlight mode for the element.

border: Highlights the element with a border outside of the selected element. This is the classic way to highlight an element of Browser librarary.

playwright: Highlights the element with Playwrights built in function.

both: Highlights the element with both methods.

Accepted values

borderplaywrightboth

HttpCredentialsTypedDict

A dictionary with known keys.

Sets the credentials for http basic-auth.

origin: Restrain sending http credentials on specific origin (scheme://host:port). Credentials for HTTP authentication. If no origin is specified, the username and password are sent to any servers upon unauthorized responses.

Can be defined as robot dictionary or as string literal. Does not reveal secrets in Robot Framework logs. Instead, username and password values are resolved internally. Please note that 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.

Example as literal:

${pwd} =    Set Variable    1234${username} =    Set Variable    adminNew Context...    httpCredentials={'username': '$username', 'password': '$pwd'}

Example as robot variable

*** Variables ***${username}=       admin${pwd}=            1234&{credentials}=    username=$username    password=$pwd*** Keywords ***Open Context   New Context    httpCredentials=${credentials}

Keys

KeyRequiredType
usernameyesstr | robot.utils.secret.Secret
passwordyesstr | robot.utils.secret.Secret
originnostr

integerStandard

Converted by Robot Framework itself.

Conversion is done using Python's int built-in function. Floating point numbers are accepted only if they can be represented as integers exactly. For example, 1.0 is accepted and 1.1 is not.

It is possible to use hexadecimal, octal and binary numbers by prefixing values with 0x, 0o and 0b, respectively. Spaces and underscores can be used as visual separators for digit grouping purposes.

Examples: 42, -1, 0b1010, 10 000 000, 0xBAD_C0FFEE

KeyActionEnum

One of a fixed set of values, written as a plain string.

Enum that defines which Keyboard Key action to perform.

Accepted values

downuppress

KeyboardInputActionEnum

One of a fixed set of values, written as a plain string.

Enum that defines how Keyboard Input adds the text into the page.

insertText is mostly similar to pasting of text.

type is similar to typing by pressing keys on the keyboard.

Accepted values

insertTexttype

LambdaFunctionCustom

Converted by the library from the string you write.

Python lambda function.

The string must start with lambda and the function must accept one argument.

Example: lambda value: value.lower().replace(' ', '')

listStandard

Converted by Robot Framework itself.

Strings must be Python list or tuple literals. They are converted using the ast.literal_eval function and possible tuples converted further to lists. They can contain any values ast.literal_eval supports, including lists and other collections.

If the argument is a list, it is used without conversion. Tuples and other sequences are converted to lists.

If the type has nested types like list[int], items are converted to those types automatically.

Examples: ['one', 'two'], [('one', 1), ('two', 2)]

Support to convert nested types is new in Robot Framework 6.0. Support for tuple literals is new in Robot Framework 7.4.

MappingStandard

Converted by Robot Framework itself.

Strings must be Python dictionary literals. They are converted to actual dictionaries using the ast.literal_eval function. They can contain any values ast.literal_eval supports, including dictionaries and other collections.

Any mapping is accepted without conversion. An exception is that if the type is MutableMapping, immutable values are converted to dict.

If the type has nested types like Mapping[str, int], items are converted to those types automatically. This in new in Robot Framework 6.0.

Examples: {'a': 1, 'b': 2}, {'key': 1, 'nested': {'key': 2}}

MediaEnum

One of a fixed set of values, written as a plain string.

Changes the CSS media type of the page.

The only allowed values are 'screen', 'print' and null. Passing null disables CSS media emulation. Using False will not define media argument.

Accepted values

screenprintnull

NewPageDetailsTypedDict

A dictionary with known keys.

Return value of New Page keyword.

page_id is the UUID of the opened page. video_path path to the video or empty string if video is not created.

Keys

KeyRequiredType
page_idyesstr
video_pathyesstr

NoneStandard

Converted by Robot Framework itself.

String NONE (case-insensitive) and the empty string are converted to the Python None object. Other values cause an error.

Converting the empty string is new in Robot Framework 7.4.

NotSetEnum

One of a fixed set of values, written as a plain string.

Defines a value that is not set.

This is used to differentiate between a value that is set to None and a value that is not set at all. Example ForcedColors has an options active, none and null. If user does not not want to give any of the ForcedColors options, user can use not_set value. Then keyword will not define ForcedColors option at all when underlying Playwright method(s) is called.

Accepted values

not_set

PdfFormatEnum

One of a fixed set of values, written as a plain string.

PDF format argument options are

Letter: 8.5in x 11in Legal: 8.5in x 14in Tabloid: 11in x 17in Ledger: 17in x 11in A0: 33.1in x 46.8in A1: 23.4in x 33.1in A2: 16.54in x 23.4in A3: 11.7in x 16.54in A4: 8.27in x 11.7in A5: 5.83in x 8.27in A6: 4.13in x 5.83in

Accepted values

LetterLegalTabloidLedgerA0A1A2A3A4A5A6

PdfMargingTypedDict

A dictionary with known keys.

Margins of the pdf.

Top margin, accepts values labeled with units. Defaults to 0px. Right margin, accepts values labeled with units. Defaults to 0px. Bottom margin, accepts values labeled with units. Defaults to 0px. Left margin, accepts values labeled with units. Defaults to 0px.

Keys

KeyRequiredType
topyesstr
rightyesstr
bottomyesstr
leftyesstr

PermissionEnum

One of a fixed set of values, written as a plain string.

Enum that defines the permission to grant to a context.

See grantPermissions(permissions) for more details.

Accepted values

accelerometeraccessibility-eventsaccessibility_eventsambient-light-sensorambient_light_sensorbackground-syncbackground_synccameraclipboard-readclipboard_readclipboard-writeclipboard_writegeolocationgyroscopelocal-network-accesslocal_network_accessmagnetometermidimidi-sysexmidi_sysexmicrophonenotificationspayment-handlerpayment_handler

PlaywrightLogTypesEnum

One of a fixed set of values, written as a plain string.

Enable low level debug information from the playwright to playwright-log.txt file.

It is possible to disable the creation of playwright-log.txt totally. Mainly useful for the library developers and for debugging purposes. Will log everything as plain text, also including secrets. If playwright-log.txt file can not be deleted, time.time_ns() is added at the end of file name. Example playwright-log-12345.txt

disabled: playwright-log.txt is not created at all. All node side logging is lost. library: Default, only logging from Browser library node side is written to the playwright-log.txt file. playwright: Also includes Playwright log messages to the playwright-log.txt file. false: Same as library and for backwards compatability. true: Same as playwright and for backwards compatibility.

Accepted values

disabledlibraryplaywrightfalsetrue

ProxyTypedDict

A dictionary with known keys.

Network proxy settings.

server 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 Optional coma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com".

username Optional username to use if HTTP proxy requires authentication.

password Optional password to use if HTTP proxy requires authentication.

Keys

KeyRequiredType
serveryesstr
bypassnostr
usernamenostr | robot.utils.secret.Secret
passwordnostr | robot.utils.secret.Secret

RecordHarTypedDict

A dictionary with known keys.

Enables HAR recording for all pages into to a file.

If not specified, the HAR is not recorded. Make sure to await context to close for the HAR 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.

Example:

${har} =    Create Dictionary     path=/path/to/har.file    omitContent=TrueNew Context    recordHar=${har}

Keys

KeyRequiredType
omitContentnobool
pathnostr

RecordVideoTypedDict

A dictionary with known keys.

Enables Video recording

Examples:

 New Context  recordVideo={'dir':'videos', 'size':{'width':400, 'height':200}} New Context  recordVideo={'dir': 'd:/automation/video'}

Keys

KeyRequiredType
dirnostr
sizenoViewportDimensions

ReducedMotionEnum

One of a fixed set of values, written as a plain string.

Emulates 'prefers-reduced-motion' media feature.

Supported values are 'reduce', 'no-preference' and null. Passing null disables reduced motion emulation.

Accepted values

reduceno_preferencenull

ReduceMotionEnum

One of a fixed set of values, written as a plain string.

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

Accepted values

reduceno_preference

RegExpCustom

Converted by the library from the string you write.

Create a (JavaScript) RegExp object from a string.

The matcher must start with a slash and end with a slash and can be followed by flags.

Example: /hello world/gi Which is equivalent to new RegExp("hello world", "gi") in JavaScript.

Following flags are supported:

Flag Description
g Global search.
i Case-insensitive search.
m Allows ^ and $ to match newline characters.
s Allows . to match newline characters.
u "unicode"; treat a pattern as a sequence of unicode code points.
y Perform a "sticky" search that matches starting at the current position in the target string.

See RegExp Object and RegExp Guide for more information.

ReloadPagesEnum

One of a fixed set of values, written as a plain string.

Defines which pages Set Storage State reloads while it restores the state.

Restoring a state file that contains IndexedDB does not finish while a page of the context holds an open connection to a database of that origin. To get around that, the pages are navigated to about:blank, the state is restored, and they are navigated back to the url they had before.

affected: Reloads the pages whose origin has IndexedDB in the state file. none: Reloads nothing. The keyword fails immediately when it detects an open connection which would block the restore. all: Reloads every page of the context.

Accepted values

affectednoneall

RequestMethodEnum

One of a fixed set of values, written as a plain string.

Enum that defines the request type.

Accepted values

HEADDELETEGETPATCHPOSTPUT

Used by

Http

ScaleEnum

One of a fixed set of values, written as a plain string.

Enum that defines the scale of the screenshot.

When set to "css", screenshot will have a single pixel per each css pixel on the page. For high-dpi devices, this will keep screenshots small. Using "device" option will produce a single pixel per each device pixel, so screenshots of high-dpi devices will be twice as large or even larger.

Accepted values

cssdevice

ScopeEnum

One of a fixed set of values, written as a plain string.

Some keywords which manipulates library settings have a scope argument. With that scope argument one can set the "live time" of that setting. Available Scopes are: Global, Suite and Test / Task. Is a scope finished, this scoped setting, like timeout, will no longer be used and the previous higher scope setting applies again.

Live Times:

  • A Global scope will live forever until it is overwritten by another Global scope. Or locally temporarily overridden by a more narrow scope.
  • A Suite scope will locally override the Global scope and live until the end of the Suite within it is set, or if it is overwritten by a later setting with Global or same scope. Children suite does inherit the setting from the parent suite but also may have its own local Suite setting that then will be inherited to its children suites.
  • A Test or Task scope will be inherited from its parent suite but when set, lives until the end of that particular test or task.

A new set higher order scope will always remove the lower order scope which may be in charge. So the setting of a Suite scope from a test, will set that scope to the robot file suite where that test is and removes the Test scope that may have been in place.

Accepted values

GlobalSuiteTestTask

ScreenshotFileTypesEnum

One of a fixed set of values, written as a plain string.

Enum that defines available file types for screenshots.

Accepted values

pngjpeg

ScreenshotReturnTypeEnum

One of a fixed set of values, written as a plain string.

Enum that defines what Take Screenshot keyword returns.

  • path returns the path to the screenshot file as pathlib.Path object.
  • path_string returns the path to the screenshot file as string.
  • bytes returns the screenshot itself as bytes.
  • base64 returns the screenshot itself as base64 encoded string.

Accepted values

pathpath_stringbytesbase64

ScrollBehaviorEnum

One of a fixed set of values, written as a plain string.

Enum that controls the behavior of scrolling.

smooth

Accepted values

autosmooth

ScrollPositionTypedDict

A dictionary with known keys.

Scroll position of an element.

Key Description
top The amount of pixel between the top border of the page and the top border of visible area.
left The amount of pixel between the left border of the page and the left border of visible area.
bottom The amount of pixel between the top border of the page and the bottom border of visible area.
right The amount of pixel between the left border of the page and the right border of visible area.

Keys

KeyRequiredType
topyesfloat
leftyesfloat
bottomyesfloat
rightyesfloat

SecretStandard

Converted by Robot Framework itself.

Encapsulates secret values to avoid them being shown in Robot Framework logs.

The value is required to be robot.api.types.Secret object. These objects encapsulate confidential values so that they are not exposed in log files. How to create them is explained in the User Guide.

New in Robot Framework 7.4.

SelectAttributeEnum

One of a fixed set of values, written as a plain string.

Enum that defines the attribute of an <option> element in a <select>-list.

This defines by what attribute an option is selected/chosen.

<select class="my_drop_down">  <option value="0: Object">None</option>  <option value="1: Object">Some</option>  <option value="2: Object">Other</option></select>

value of the first option would be 0: Object.

label / text both defines the innerText which would be None for first element.

index 0 indexed number of an option. Would be 0 for the first element.

Accepted values

valuelabeltextindex

SelectionStrategyEnum

One of a fixed set of values, written as a plain string.

SelectionStrategy to be used. Refers to Playwrights page.getBy*** functions. See Playwright Locators

AltText

All images should have an alt attribute that describes the image. You can locate an image based on the text alternative using page.getByAltText().

For example, consider the following DOM structure.

<img alt="playwright logo" src="/img/playwright-logo.svg" width="100" />

Label

Allows locating input elements by the text of the associated <label> or aria-labelledby element, or by the aria-label attribute.

For example, this method will find inputs by label "Username" and "Password" in the following DOM:

<input aria-label="Username"><label for="password-input">Password:</label><input id="password-input">

Placeholder

Allows locating input elements by the placeholder text.

Example:

<input type="email" placeholder="name@example.com" />

TestId

Locate element by the test id.

Currently only the exact attribute data-testid is supported.

Example:

<button data-testid="directions">Itinéraire</button>

Text

Allows locating elements that contain given text.

Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace. Input elements of the type button and submit are matched by their value instead of the text content. For example, locating by text "Log in" matches <input type=button value="Log in">.

Title

Allows locating elements by their title attribute.

Example:

<img alt="playwright logo" src="/img/playwright-logo.svg" title="Playwright" width="100" />

Accepted values

AltTextLabelPlaceholderTestIDTextTitle

SelectionTypeEnum

One of a fixed set of values, written as a plain string.

Enum that defines if the current id or all ids shall be returned.

ACTIVE / CURRENT defines to return only the id of the currently active instance of a Browser/Context/Page.

ALL / ANY defines to return ids of all instances.

Accepted values

CURRENTACTIVEALLANY

SelectOptionsTypedDict

A dictionary with known keys.

Dictionary with the following keys and their values "index", "value", "label" and "selected".

Keys Description
index 0 based index of the option.
value Value attribute of the option.
label Label/Text of the option.
selected Boolean if the option is selected.

Keys

KeyRequiredType
indexyesint
valueyesstr
labelyesstr
selectedyesbool

ServiceWorkersPermissionsEnum

One of a fixed set of values, written as a plain string.

Whether to allow sites to register Service workers.

allow: Service Workers can be registered.

block: Playwright will block all registration of Service Workers.

Accepted values

allowblock

SizeFieldsEnum

One of a fixed set of values, written as a plain string.

Enum that defines how the returned size is filtered.

ALL defines that the size is returned as a dictionary. {'width': <float>, 'height': <float>}.

width / height will return a single float value of the chosen dimension.

Accepted values

widthheightALL

stringStandard

Converted by Robot Framework itself.

All arguments are converted to Unicode strings.

Most values are converted simply by using str(value). An exception is that bytes are mapped directly to Unicode code points with same ordinals. This means that, for example, b"hyv\xe4" becomes "hyvä".

Converting bytes specially is new Robot Framework 7.4.

SupportedBrowsersEnum

One of a fixed set of values, written as a plain string.

Defines which browser shall be started.

Browser Browser with this engine
chromium Google Chrome, Microsoft Edge (since 2020), Opera
firefox Mozilla Firefox
webkit Apple Safari, Mail, AppStore on MacOS and iOS

Since Playwright comes with a pack of builtin binaries for all browsers, no additional drivers e.g. geckodriver are needed.

All these browsers that cover more than 85% of the world wide used browsers, can be tested on Windows, Linux and MacOS. Theres is not need for dedicated machines anymore.

Accepted values

chromiumfirefoxwebkit

TextTypeEnum

One of a fixed set of values, written as a plain string.

Defines which Playwright method is used to get the text of an element.

allInnerTexts: Returns a list of node.innerText values for all matching nodes.

allTextContents: Returns a list of node.textContent values for all matching nodes.

innerText: Returns the element node.innerText value, which represents the rendered text content of a node and its descendants.

inputValue: Returns the value for the matching <input> or <textarea> or <select> element.

innerHTML: Returns the element node.innerHTML value, which is the HTML markup contained within the element, omitting any shadow roots.

Accepted values

allInnerTextsallTextContentsinnerTextinputValueinnerHTML

timedeltaStandard

Converted by Robot Framework itself.

Strings are expected to represent a time interval in one of the time formats Robot Framework supports:

  • a number representing seconds like 42 or 10.5
  • a time string like 1 hour 2 seconds or 1h 2s
  • a "timer" string like 01:02 (1 minute 2 seconds) or 01:00:03 (1 hour 3 seconds)

Integers and floats are considered to be seconds.

See the Robot Framework User Guide for more details about the supported time formats.

TracingGroupModeEnum

One of a fixed set of values, written as a plain string.

Defines in what detail level keywords are written to Playwright trace.

Playwrright trace is a full log of all playwright actions and events that happen in the browser during the test run. This includes all API calls, events, logs, network requests, and responses as well as the DOM at every moment during execution. This trace can be activated with the tracing parameter of New Context keyword.

  • Full All keyword calls are written to trace as groups even if they do not call Browser keywords.
  • Browser Just Browser library keywords are written to the logs as groups.
  • Playwright No additional keywords are logged, just the Playwright API calls.

Accepted values

FullBrowserPlaywright

tupleStandard

Converted by Robot Framework itself.

Strings must be Python tuple or list literals. They are converted using the ast.literal_eval function and possible lists converted further to tuples. They can contain any values ast.literal_eval supports, including tuples and other collections.

If the argument is a tuple, it is used without conversion. Lists and other sequences are converted to tuples.

If the type has nested types like tuple[str, int, int], items are converted to those types automatically.

Examples: ('one', 'two'), (('one', 1), ('two', 2))

Support to convert nested types is new in Robot Framework 6.0. Support for list literals is new in Robot Framework 7.4.

ViewportDimensionsTypedDict

A dictionary with known keys.

Viewport dimensions.

Viewport is the browsers inner window size that is used to display the page.

Key Description
width page width in pixels.
height page height in pixels.

Keys

KeyRequiredType
widthyesint
heightyesint