BROWSER
Documentation— open the keyword list

147 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 19.12.619 modules77 argument types

Introduction

Generated from the library's Libdoc for 19.12.6. 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 information about installation, support, and more please visit the project pages. 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 with three different layers that build on each other: Browser, Context and Page.

Browsers

A browser can be started with one of the three different engines Chromium, Firefox or Webkit.

Supported Browsers

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. There is no need for dedicated machines anymore.

A browser process is started headless (without a GUI) by default. Run New Browser with specified arguments if a browser with a GUI is requested or if a proxy has to be configured. A browser process can contain several contexts.

Contexts

A context corresponds to a set of independent incognito pages in a browser that share cookies, sessions or profile settings. Pages in two separate contexts do not share cookies, sessions or profile settings. Compared to Selenium, these do not require their own browser process. To get a clean environment a test can just open a new context. Due to this new independent browser sessions can be opened with Robot Framework Browser about 10 times faster than with Selenium by just opening a New Context within the opened browser.

To make pages in the same suite share state, use the same context by opening the context with New Context on suite setup.

The context layer is useful e.g. for testing different user sessions on the same webpage without opening a whole new browser context. Contexts can also have detailed configurations, such as geo-location, language settings, the viewport size or color scheme. Contexts do also support http credentials to be set, so that basic authentication can also be tested. To be able to download files within the test, the acceptDownloads argument must be set to True in New Context keyword. A context can contain different pages.

Pages

A page does contain the content of the loaded web site and has a browsing history. Pages and browser tabs are the same.

Typical usage could be:

* Test Cases *Starting a browser with a page    New Browser    chromium    headless=false    New Context    viewport={'width': 1920, 'height': 1080}    New Page       https://marketsquare.github.io/robotframework-browser/Browser.html    Get Title      ==    Browser

The Open Browser keyword opens a new browser, a new context and a new page. This keyword is useful for quick experiments or debugging sessions.

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

Each Browser, Context and Page has a unique ID with which they can be addressed. A full catalog of what is open can be received by Get Browser Catalog as a dictionary.

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

All keywords in the library that need to interact with an element on a web page take an argument typically named selector that specifies how to find the element. Keywords can find elements with strict mode. If strict mode is true and locator finds multiple elements from the page, keyword will fail. If keyword finds one element, keyword does not fail because of strict mode. If strict mode is false, keyword does not fail if selector points many elements. Strict mode is enabled by default, but can be changed in library importing or Set Strict Mode keyword. Keyword documentation states if keyword uses strict mode. If keyword does not state that strict mode is used, then strict mode is not applied for the keyword. For more details, see Playwright strict documentation.

Selector strategies that are supported by default are listed in the table below.

Strategy Match based on Example
css CSS selector. css=.class > \#login_btn
xpath XPath expression. xpath=//input[@id="login_btn"]
text Browser text engine. text=Login
id Element ID Attribute. id=login_btn

CSS Selectors can also be recorded with Record selector keyword.

Explicit Selector Strategy

The explicit selector strategy is specified with a prefix using syntax strategy=value. Spaces around the separator are ignored, so css=foo, css= foo and css = foo are all equivalent.

Implicit Selector Strategy

The default selector strategy is css.

If selector does not contain one of the know explicit selector strategies, it is assumed to contain css selector.

Selectors that are starting with // or .. are considered as xpath selectors.

Selectors that are in quotes are considered as text selectors.

Examples:

# CSS selectors are default.Click  span > button.some_class         # This is equivalentClick  css=span > button.some_class     # to this.# // or .. leads to xpath selector strategyClick  //span/button[@class="some_class"]Click  xpath=//span/button[@class="some_class"]# "text" in quotes leads to exact text selector strategyClick  "Login"Click  text="Login"

CSS

As written before, the default selector strategy is css. See css selector for more information.

Any malformed selector not starting with // or .. nor starting and ending with a quote is assumed to be a css selector.

Note that # is a comment character in Robot Framework syntax and needs to be escaped like \# to work as a css ID selector.

Examples:

Click  span > button.some_classGet Text  \#username_field  ==  George

XPath

XPath engine is equivalent to Document.evaluate. Example: xpath=//html/body//span[text()="Hello World"].

Malformed selector starting with // or .. is assumed to be an xpath selector. For example, //html/body is converted to xpath=//html/body. More examples are displayed in Examples.

Note that xpath does not pierce shadow_roots.

Text

Text engine finds an element that contains a text node with the passed text. For example, Click text=Login clicks on a login button, and Wait For Elements State text="lazy loaded text" waits for the "lazy loaded text" to appear in the page.

Text engine finds fields based on their labels in text inserting keywords.

Malformed selector starting and ending with a quote (either " or ') is assumed to be a text selector. For example, Click "Login" is converted to Click text="Login". Be aware that these leads to exact matches only! More examples are displayed in Examples.

Insensitive match

By default, the match is case-insensitive, ignores leading/trailing whitespace and searches for a substring. This means text= Login matches <button>Button loGIN (click me)</button>.

Exact match

Text body can be escaped with single or double quotes for precise matching, insisting on exact match, including specified whitespace and case. This means text="Login " will only match <button>Login </button> with exactly one space after "Login". Quoted text follows the usual escaping rules, e.g. use \" to escape double quote in a double-quoted string: text="foo\"bar".

RegEx

Text body can also be a JavaScript-like regex wrapped in / symbols. This means text=/^hello .*!$/i or text=/^Hello .*!$/ will match <span>Hello Peter Parker!</span> with any name after Hello, ending with !. The first one flagged with i for case-insensitive. See https://regex101.com for more information about RegEx.

Button and Submit Values

Input elements of the type button and submit are rendered with their value as text, and text engine finds them. For example, text=Login matches <input type=button value="Login">.

Cascaded selector syntax

Browser library supports the same selector strategies as the underlying Playwright node module: xpath, css, id and text. The strategy can either be explicitly specified with a prefix or the strategy can be implicit.

A major advantage of Browser is that multiple selector engines can be used within one selector. It is possible to mix XPath, CSS and Text selectors while selecting a single element.

Selectors are strings that consists of one or more clauses separated by >> token, e.g. clause1 >> clause2 >> clause3. When multiple clauses are present, next one is queried relative to the previous one's result. Browser library supports concatenation of different selectors separated by >>.

For example:

Highlight Elements    "Hello" >> ../.. >> .select_buttonHighlight Elements    text=Hello >> xpath=../.. >> css=.select_button

Each clause contains a selector engine name and selector body, e.g. engine=body. Here engine is one of the supported engines (e.g. css or a custom one). Selector body follows the format of the particular engine, e.g. for css engine it should be a css selector. Body format is assumed to ignore leading and trailing white spaces, so that extra whitespace can be added for readability. If the selector engine needs to include >> in the body, it should be escaped inside a string to not be confused with clause separator, e.g. text="some >> text".

Selector engine name can be prefixed with * to capture an element that matches the particular clause instead of the last one. For example, css=article >> text=Hello captures the element with the text Hello, and *css=article >> text=Hello (note the *) captures the article element that contains some element with the text Hello.

For convenience, selectors in the wrong format are heuristically converted to the right format. See Implicit Selector Strategy

Examples

# queries 'div' css selectorGet Element    css=div# queries '//html/body/div' xpath selectorGet Element    //html/body/div# queries '"foo"' text selectorGet Element    text=foo# queries 'span' css selector inside the result of '//html/body/div' xpath selectorGet Element    xpath=//html/body/div >> css=span# converted to 'css=div'Get Element    div# converted to 'xpath=//html/body/div'Get Element    //html/body/div# converted to 'text="foo"'Get Element    "foo"# queries the div element of every 2nd span element inside an element with the id fooGet Element    \#foo >> css=span:nth-child(2n+1) >> divGet Element    id=foo >> css=span:nth-child(2n+1) >> div

Be aware that using # as a starting character in Robot Framework would be interpreted as comment. Due to that fact a #id must be escaped as \#id.

iFrames

By default, selector chains do not cross frame boundaries. It means that a simple CSS selector is not able to select an element located inside an iframe or a frameset. For this use case, there is a special selector >>> which can be used to combine a selector for the frame and a selector for an element inside a frame.

Given this simple pseudo html snippet:

<iframe id="iframe" src="src.html">  #document    <!DOCTYPE html>    <html>      <head></head>      <body>        <button id="btn">Click Me</button>      </body>    </html></iframe>

Here's a keyword call that clicks the button inside the frame.

Click   id=iframe >>> id=btn

The selectors on the left and right side of >>> can be any valid selectors. The selector clause directly before the frame opener >>> must select the frame element itself. Frame selection is the only place where Browser Library modifies the selector, as explained in above. In all cases, the library does not alter the selector in any way, instead it is passed as is to the Playwright side.

If multiple keyword shall be performed inside a frame, it is possible to define a selector prefix with Set Selector Prefix. If this prefix is set to a frame/iframe it has similar behavior as SeleniumLibrary keyword Select Frame.

WebComponents and Shadow DOM

Playwright and so also Browser are able to do automatic piercing of Shadow DOMs and therefore are the best automation technology when working with WebComponents.

Also other technologies claim that they can handle Shadow DOM and Web Components. However, none of them do pierce shadow roots automatically, which may be inconvenient when working with Shadow DOM and Web Components.

For that reason, the css engine pierces shadow roots. More specifically, every Descendant combinator pierces an arbitrary number of open shadow roots, including the implicit descendant combinator at the start of the selector.

That means, it is not necessary to select each shadow host, open its shadow root and select the next shadow host until you reach the element that should be controlled.

CSS:light

css:light engine is equivalent to Document.querySelector and behaves according to the CSS spec. However, it does not pierce shadow roots.

css engine first searches for elements in the light dom in the iteration order, and then recursively inside open shadow roots in the iteration order. It does not search inside closed shadow roots or iframes.

Examples:

<article>  <div>In the light dom</div>  <div slot='myslot'>In the light dom, but goes into the shadow slot</div>  <open mode shadow root>      <div class='in-the-shadow'>          <span class='content'>              In the shadow dom              <open mode shadow root>                  <li id='target'>Deep in the shadow</li>              </open mode shadow root>          </span>      </div>      <slot name='myslot'></slot>  </open mode shadow root></article>

Note that <open mode shadow root> is not an html element, but rather a shadow root created with element.attachShadow({mode: 'open'}).

  • Both "css=article div" and "css:light=article div" match the first <div>In the light dom</div>.
  • Both "css=article > div" and "css:light=article > div" match two div elements that are direct children of the article.
  • "css=article .in-the-shadow" matches the <div class='in-the-shadow'>, piercing the shadow root, while "css:light=article .in-the-shadow" does not match anything.
  • "css:light=article div > span" does not match anything, because both light-dom div elements do not contain a span.
  • "css=article div > span" matches the <span class='content'>, piercing the shadow root.
  • "css=article > .in-the-shadow" does not match anything, because <div class='in-the-shadow'> is not a direct child of article
  • "css:light=article > .in-the-shadow" does not match anything.
  • "css=article li#target" matches the <li id='target'>Deep in the shadow</li>, piercing two shadow roots.

text:light

text engine open pierces shadow roots similarly to css, while text:light does not. Text engine first searches for elements in the light dom in the iteration order, and then recursively inside open shadow roots in the iteration order. It does not search inside closed shadow roots or iframes.

id, data-testid, data-test-id, data-test and their :light counterparts

Attribute engines are selecting based on the corresponding attribute value. For example: data-test-id=foo is equivalent to css=[data-test-id="foo"], and id:light=foo is equivalent to css:light=[id="foo"].

Element reference syntax

It is possible to get a reference to a Locator by using Get Element and Get Elements keywords. Keywords do not save reference to an element in the HTML document, instead it saves reference to a Playwright Locator. In nutshell Locator captures the logic of how to retrieve that element from the page. Each time an action is performed, the locator re-searches the elements in the page. This reference can be used as a first part of a selector by using a special selector syntax element=. like this:

${ref}=    Get Element    .some_class           Click          ${ref} >> .some_child     # Locator searches an element from the page.           Click          ${ref} >> .other_child    # Locator searches again an element from the page.

The .some_child and .other_child selectors in the example are relative to the element referenced by ${ref}. Please note that frame piercing is not possible with element reference.

Assertions

Keywords that accept arguments assertion_operator <AssertionOperator> and assertion_expected can optionally assert that a specified condition holds. Keywords will return the value even when the assertion is performed by the keyword.

Assert will retry and fail only after a specified timeout. See Importing and retry_assertions_for (default is 1 second) for configuring this timeout.

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.

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.

By default, keywords will provide an error message if an assertion fails. Default error messages can be overwritten with a message argument. The message argument accepts {value}, {value_type}, {expected} and {expected_type} format options. The {value} is the value returned by the keyword and the {expected} is the expected value defined by the user, usually the value in the assertion_expected argument. The {value_type} and {expected_type} are the type definitions from {value} and {expected} arguments. In similar fashion as Python type returns type definition. Assertions will retry until timeout has expired if they do not pass.

The assertion assertion_expected value is not converted by the library and is used as is. Therefore when assertion is made, the assertion_expected argument value and value returned the keyword must have the same type. If types are not the same, assertion will fail. Example Get Text always returns a string and has to be compared with a string, even the returned value might look like a number.

Other Keywords have other specific types they return. Get Element Count always returns an integer. Get Bounding Box and Get Viewport Size can be filtered. They return a dictionary without a filter and a number when filtered. These Keywords do automatic conversion for the expected value if a number is returned.

* < less or greater > With Strings* Comparisons of strings with greater than or less than compares each character, starting from 0 regarding where it stands in the code page. Example: A < Z, Z < a, ac < dc It does never compare the length of elements. Neither lists nor strings. The comparison stops at the first character that is different. Examples: `'abcde' < 'abd', '100.000' < '2' In Python 3 and therefore also in Browser it is not possible to compare numbers with strings with a greater or less operator. On keywords that return numbers, the given expected value is automatically converted to a number before comparison.

The getters Get Page State and Get Browser Catalog return a dictionary. Values of the dictionary can directly asserted. Pay attention of possible types because they are evaluated in Python. For example:

Get Page State    validate    2020 >= value['year']                     # Comparison of numbersGet Page State    validate    "IMPORTANT MESSAGE!" == value['message']  # Comparison of strings

The 'then' or 'evaluate' closure

Keywords that accept arguments assertion_operator and assertion_expected can optionally also use then or evaluate closure to modify the returned value with BuiltIn Evaluate. Actual value can be accessed with value.

For example Get Title then 'TITLE: '+value. See Builtin Evaluating expressions for more info on the syntax.

Examples

# Keyword    Selector                    Key        Assertion Operator    Assertion ExpectedGet Title                                           equal                 Page TitleGet Title                                           ^=                    PageGet Style    //*[@id="div-element"]      width      >                     100Get Title                                           matches               \\w+\\s\\w+Get Title                                           validate              value == "Login Page"Get Title                                           evaluate              value if value == "some value" else "something else"

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

Browser library integrated nodejs and python. The NodeJS side can be also executed as a standalone process. Browser libraries running on the same machine can talk to that instead of starting new node processes. This can speed execution when running tests parallel. To start node side run on the directory when the Browser package is PLAYWRIGHT_BROWSERS_PATH=0 node Browser/wrapper/index.js PORT.

PORT is the port you want to use for the node process. To execute tests then with pabot for example do ROBOT_FRAMEWORK_BROWSER_NODE_PORT=PORT pabot ...

Experimental: Provide parameters to node process

Browser library is integrated with NodeJSand and Python. Browser library starts a node process, to communicate Playwright API in NodeJS side. It is possible to provide parameters for the started node process by defining ROBOT_FRAMEWORK_BROWSER_NODE_DEBUG_OPTIONS environment variable, before starting the test execution. Example: ROBOT_FRAMEWORK_BROWSER_NODE_DEBUG_OPTIONS=--inspect;robot path/to/tests. There can be multiple arguments defined in the environment variable and arguments must be separated with comma.

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.

Extending Browser library with a JavaScript module

Browser library can be extended with JavaScript. The module must be in CommonJS format that Node.js uses. You can translate your ES6 module to Node.js CommonJS style with Babel. Many other languages can be also translated to modules that can be used from Node.js. For example TypeScript, PureScript and ClojureScript just to mention few.

async function myGoToKeyword(url, args, page, logger, playwright) {  logger(args.toString())  playwright.coolNewFeature()  return await page.goto(url);}

Functions can contain any number of arguments and arguments may have default values.

There are some reserved arguments that are not accessible from Robot Framework side. They are injected to the function if they are in the arguments:

page: the playwright Page object.

context: the playwright BrowserContext object.

browser: the playwright Browser object.

args: the rest of values from Robot Framework keyword call *args.

logger: callback function that takes strings as arguments and writes them to robot log. Can be called multiple times.

playwright: playwright module (* from 'playwright'). Useful for integrating with Playwright features that Browser library doesn't support with it's own keywords. API docs

also argument name self can not be used.

Example module.js

async function myGoToKeyword(pageUrl, page) {  await page.goto(pageUrl);  return await page.title();}exports.__esModule = true;exports.myGoToKeyword = myGoToKeyword;

Example Robot Framework side

* Settings *Library   Browser  jsextension=${CURDIR}/module.js* Test Cases *Hello  New Page  ${title}=  myGoToKeyword  https://playwright.dev  Should be equal  ${title}  Playwright

Also selector syntax can be extended with a custom selector using a js module

Example module keyword for custom selector registering

async function registerMySelector(playwright) {playwright.selectors.register("myselector", () => ({   // Returns the first element matching given selector in the root's subtree.   query(root, selector) {      return root.querySelector(a[data-title="${selector}"]);    },    // Returns all elements matching given selector in the root's subtree.    queryAll(root, selector) {      return Array.from(root.querySelectorAll(a[data-title="${selector}"]));    }}));return 1;}exports.__esModule = true;exports.registerMySelector = registerMySelector;

Plugins

Browser library offers plugins as a way to modify and add library keywords and modify some of the internal functionality without creating a new library or hacking the source code. See plugin API documentation for further details.

Language

Browser library offers possibility to translate keyword names and documentation to new language. If language is defined, Browser library will search from module search path Python packages starting with robotframework_browser_translation by using Python pluging API. Library is using naming convention to find Python plugins.

The package must implement single API call, get_language without any arguments. Method must return a dictionary containing two keys: language and path. The language key value defines which language the package contains. Also value should match (case insensitive) the library language import parameter. The path parameter value should be full path to the translation file.

Translation file

The file name or extension is not important, but data must be in json format. The keys of json are the methods names, not the keyword names, which implements keywords. Value of key is json object which contains two keys: name and doc. The name key contains the keyword translated name and doc contains translated documentation. Providing doc and name are optional, example translation json file can only provide translations to keyword names or only to documentation. But it is always recommended to provide translation to both name and doc. Special key __intro__ is for class level documentation and __init__ is for init level documentation. These special values name can not be translated, instead name should be kept the same.

Generating template translation file

Template translation file, with English language can be created by running: rfbrowser translation /path/to/translation.json command. Command does not provide translations to other languages, it only provides easy way to create full list keywords and their documentation in correct format. It is also possible to add keywords from library plugins and js extensions by providing --plugings and --jsextension arguments to command. Example: rfbrowser translation --plugings myplugin.SomePlugin --jsextension /path/ot/jsplugin.js /path/to/translation.json

Example project for translation can be found from robotframework-browser-translation-fi repository.

Keywords 147

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, example "Accept Cookies" dialog might appear and block the interaction with the page, like Click keyword. These overlays can be problematic to handle, because they might appear randomly in the page. This keyword allows to create automatic method, which will close those overlays by clicking the element indicated by click_selector. Handler is activated when element indicated by selector is visible. For further information, see Playwright's addLocatorHandler method.

Arguments Description
selector Is the selector to the element which indicated that locator handler should be called.
noWaitAfter By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then library will continue with the action/assertion that triggered the handler. This option allows to opt-out of this behavior, so that overlay can stay visible after the handler has run.
times Is the number of times to how often locator handler is is called. None is unlimited.
click_selector Is the selector to the element to be clicked.
click_clickCount Is the number of times to click the element.
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 are same as Click keyword. 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 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:button    # 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 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 indicated that locator handler should be called.
noWaitAfter By default, after calling the handler Playwright will wait until the overlay becomes hidden, and only then library will continue with the action/assertion that triggered the handler. This option allows to opt-out of this behavior, so that overlay can stay visible after the handler has run.
times Is the number of times to how often locator handler is is called. None is unlimited.
handler_spec Is a list of dictionaries which defines the actions to be performed.

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 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. Additional keys are passed to the action as keyword arguments. Example for the click action refer to the Playwright's documentation which options are possible.

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 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 to convert the values to the correct type. Example if timeout is needed, the value must be converted to a number in 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 will click the button id=ButtonInOverlayType 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 99

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.

Arguments Description
content Raw CSS content to be injected into frame.

Example:

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

Comment >>

JavaScript Evaluation, line 138

Advance Clock

Advance the clock by a specified amount of time.

Arguments

NameDefaultType
timerequiredtimedelta
advance_type=fast_forwardCLockAdvanceType

Tags

ClockSetter

Documentation

Advance the clock by a specified amount of time.

Argument Description
time The time to advance.
advance_type The type of advance. Default is fast_forward.

The run_forward advances the clock by firing all the time-related callbacks. The fast_forward advances the clock by jumping forward in time. Only 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 [https://playwright.dev/docs/actionability 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 668

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 118

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 matches selector. If there is none, wait until a matching element is attached to the DOM.
  • Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  • Scroll the element into view if needed.
  • Use Mouse Button to click in the center of the element, or the specified position.
  • Wait for initiated navigation to either succeed or fail.
Arguments Description
selector Selector element to click. See the Finding elements section for details about the selectors.
button Defaults to left if invalid.

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

Example:

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

Comment >>

Interaction, line 305

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 matches selector. If there is none, wait until a matching element is attached to the DOM.
  • Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  • Scroll the element into view if needed.
  • Use Mouse Button to click in the center of the element, or the specified position.
  • Wait for initiated navigation to either succeed or fail, unless noWaitAfter option is set.
Arguments Description
selector Selector element to click. See the Finding elements section for details about the selectors.
button Defaults to left if invalid.
*modifiers Modifier keys to press. Ensures that only these modifiers are pressed during the click, and then restores current modifiers back. If not specified, currently pressed modifiers are used. Modifiers can be specified in any order, and multiple modifiers can be specified. Valid modifier keys are Control, Alt, Shift and Meta. Due to the fact that the argument *modifiers is a positional only argument, all preceding keyword arguments have to be specified as positional arguments before *modifiers.
clickCount Defaults to 1.
delay Time to wait between mouse-down and mouse-up. Defaults to 0.
position_x position_y A point to click relative to the top-left corner of element bounding-box. Only positive values within the bounding-box are allowed. If not specified, clicks to some visible point of the element.
force Set to True to skip Playwright's Actionability checks (https://playwright.dev/docs/actionability).
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 333

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 117

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 547

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 closes all contexts. When a context id is provided, that context is closed.
browser Browser where to close context. CURRENT selects the active browser. ALL closes all browsers. When a browser id is provided, that browser is closed.
save_trace If set to False, the trace of this context is not saved, even if it was enables by New Context. Defaults to True.

Example:

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

Comment >>

Browser, Context & Page, line 164

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 closes all pages. When a page id is provided, that page is closed.
context Context where to close page. CURRENT selects the active context. ALL closes all contexts. When a context id is provided, that context is closed.
browser Browser where to close page. CURRENT selects the active browser. ALL closes all browsers. When a browser id is provided, that browser is closed.

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 268

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. Pass 0 to disable timeout.

To Connect to a Browser viw Chrome DevTools Protocol, the browser must be started with this protocol enabled. This 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 379

Crawl Site

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

Arguments

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.

returns list of crawled urls.

Arguments Description
url is the page to start crawling from.
page_crawl_keyword is the keyword that will be executed on every page. By default it will take a screenshot on every page.
max_number_of_page_to_crawl is the upper limit of pages to crawl. Crawling will stop if the number of crawled pages goes over this.
max_depth_to_crawl is the upper limit of consecutive links followed from the start page. Crawling will stop if there are no more links under this depth.

Comment >>

Crawling, line 13

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

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 784

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 is 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,}

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. This keyword requires that there is currently an open page. The keyword uses the current pages local state (cookies, sessionstorage, localstorage) for the download to avoid authentication problems.

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 154

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, which center is the start-point.
selector_to Identifies the element, which center is the end-point.
steps Defines how many intermediate mouse move events are sent. 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 boundingbox.

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

Example

Drag And Drop    "Circle"    "Goal"

Comment >>

Interaction, line 1072

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.

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 1117

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, which center is the start-point.
x & y identifies the end-point which is relative to the start-point.
steps defines how many intermediate mouse move events are sent. 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 boundingbox), 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 pixel to the left

Comment >>

Interaction, line 1151

Emulate Media

Changes the CSS media type.

Arguments

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

Tags

PageContentSetter

Documentation

Changes the CSS media type.

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

Arguments Description
colorScheme Emulates prefers-colors-scheme media feature, supported values are 'light' and 'dark'. Passing null disables color scheme emulation. 'no-preference' is deprecated.
forcedColors Emulates '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 'prefers-reduced-motion' media feature, supported values are 'reduce', 'no-preference'. Passing null disables reduced motion emulation.

PDF, line 152

Evaluate JavaScript

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

Arguments

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

Returns

Any

Tags

GetterPageContentSetter

Documentation

Executes given javascript on the selected element(s) or on 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 elementHandle. For example (element) => document.activeElement === element See the Finding elements section for details about the selectors.
*function A valid javascript function or a javascript function body. These arguments can be used to write readable multiline JavaScript.
arg an additional argument that can be handed over to the JavaScript function. This argument must be JSON serializable. ElementHandles are not supported.
all_elements defines if only the single elementHandle found by selector is handed over to the function or if set to True all found elements are handed over as array.

Example with all_elements=True:

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

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

Usage examples.

Comment >>

JavaScript Evaluation, line 28

Fill Secret

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

Arguments

NameDefaultType
selectorrequiredstr
secretrequiredstr
force=Falsebool

Tags

PageContentSetter

Documentation

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

Arguments Description
secret The secret string that should be filled into the text field.
selector Selector of the text field. See the Finding elements section for details about the selectors.
force Set to True to skip Playwright's [https://playwright.dev/docs/actionability Actionability checks].

This keyword does not log secret in Robot Framework logs, when keyword resolves the secret variable internally. When secret variable is prefixed with $, without the curly braces, library will resolve the corresponding Robot Framework variable.

If secret variable is prefixed with %, library will resolve corresponding environment variable. Example $Password` will resolve to ${Password} Robot Framework variable. Also %ENV_PWD will resolve to %{ENV_PWD} environment variable.

Using normal Robot Framework variables like ${password} will not work!

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

This keyword will also work with a give cryptographic cipher text, that has been encrypted by Crypto library. See Crypto Library for more details.

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.

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 variablesFill Secret    input#username_field    %username    # Keyword resolves variable value from environment variables

Comment >>

Interaction, line 201

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 method waits for an element matching the selector to appear, waits for actionability checks, focuses the element, fills it and triggers an input event after filling.

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

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 [https://playwright.dev/docs/actionability 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 88

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's no element matching selector, the method waits until a matching element appears in the DOM. Timeouts after 10 seconds.

Comment >>

Interaction, line 546

Get Aria Snapshot

Returns the aria snapshot of the element found by selector.

Arguments

NameDefaultType
selectorrequiredstr
return_type=yamlAriaSnapshotReturnType
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

Union

Tags

AssertionGetterPageContent

Documentation

Returns the aria snapshot 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.
return_type Defines the return type. Possible values are yaml (default) and dict. If yaml is selected, the returned value is a string in YAML format. If dict is selected, the returned value is a dictionary.
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 state 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 63

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 a attribute is selected that is not present and no assertion operator is set, the keyword fails. If an assertion operator is set and the attribute is not present, the returned value is None. This can be used to assert check the presents or the absents of an attribute.

Example Element:

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

Example Code:

Get Attribute   id=enabled_button    disabled                   # FAIL => "Attribute 'disabled' not found!"Get Attribute   id=enabled_button    disabled     ==    ${None}     # PASS => returns: 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 336

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 attribute names do match to the expected value. See Assertions for further details for the assertion arguments. By default assertion is not done.

Available assertions:

  • == , != and contains / *= can work with multiple values
  • validate and evaluate only accepts 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 399

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

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 1036

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, ACTIVE for the currently active browser or the id of the browser to get the ids from.

The ACTIVE browser is a synonym for the CURRENT Browser.

Comment >>

Browser, Context & Page, line 1471

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

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 accepts one single expected value

Other operators are not allowed.

Example:

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

Comment >>

Getters & Assertions, line 452

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

Dimensions

Tags

AssertionGetterPageContent

Documentation

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

Arguments Description
selector Optional selector from which shall be retrieved. If no selector is given the client size of the page itself is used (document.scrollingElement). See the Finding elements section for details about the selectors.
key Optionally filters the returned values. If keys is set to ALL (default) it will return the scroll size as dictionary, otherwise it will just return the single value selected by the key.
assertion_operator See Assertions for further details. Defaults to None.
assertion_expected Expected value for the counting
message overrides the default error message for assertion.

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

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

See Get BoundingBox or Get Scroll Size for examples.

Comment >>

Getters & Assertions, line 1386

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 int for number of entries or timedelta for time period.

The returned data is a list of log messages.

A log message is a dict 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 1138

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

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

Comment >>

Browser, Context & Page, line 1503

Get Cookies

Returns cookies from the current active browser context.

Arguments

NameDefaultType
return_type=dictionaryCookieType

Returns

Union

Tags

GetterPageContent

Documentation

Returns cookies from the current active browser context.

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

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

Comment >>

Cookies, line 28

Get Device

Get a single device descriptor with name exactly matching name.

Arguments

NameDefaultType
namerequiredstr

Returns

dict

Tags

BrowserControlGetter

Documentation

Get a single device descriptor with name exactly matching name.

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

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

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

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

Comment >>

Devices, line 39

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 1522

Get Element

Returns a reference to a Playwright [https://playwright.dev/docs/api/class-locator|Locator].

Arguments

NameDefaultType
selectorrequiredstr

Returns

str

Tags

GetterPageContent

Documentation

Returns a reference to a Playwright Locator.

The reference can be used in subsequent selectors.

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

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

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 902

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
locator_type 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. Default 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 1058

Get Element By Role

Returns a reference to Playwright [https://playwright.dev/docs/api/class-locator|Locator] for the matched element by role or a list of references 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 reference to Playwright Locator for the matched element by role or a list of references if all_elements is set to True.

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 it's 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 963

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 counting
message overrides the default error message for assertion.

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

Example:

Get Element Count    label    >    1

Comment >>

Getters & Assertions, line 670

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 contain 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. Select elements have also either selected or unselected.

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

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

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

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

Comment >>

Getters & Assertions, line 1436

Get Elements

Returns a reference to Playwright [https://playwright.dev/docs/api/class-locator|Locator] for all matched elements by selector.

Arguments

NameDefaultType
selectorrequiredstr

Returns

list

Tags

GetterPageContent

Documentation

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

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

Example:

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

Comment >>

Getters & Assertions, line 929

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

dict

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 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 int for number of entries or timedelta for time period.

The returned data is a list of error messages.

An error message is a dict 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 1210

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 1587

Get Page Source

Gets pages HTML source as a string.

Arguments

NameDefaultType
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

str

Tags

AssertionGetterPageContent

Documentation

Gets pages 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 there need to get element html, use Get Property instead. Example:

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

Comment >>

Getters & Assertions, line 147

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 property is not found, value is None and Keyword does not fail. See Get Attribute for examples.

Example:

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

Comment >>

Getters & Assertions, line 277

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 shall be retrieved. If no selector is given the client size of the page itself is used (document.scrollingElement). See the Finding elements section for details about the selectors.
key Optionally filters the returned values. If keys is set to ALL (default) it will return the scroll position as dictionary, otherwise it will just return the single value selected by the key.
assertion_operator See Assertions for further details. Defaults to None.
assertion_expected Expected value for the counting
message overrides the default error message for assertion.

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

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

See Get BoundingBox or Get Scroll Size for examples.

Comment >>

Getters & Assertions, line 1330

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 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 counting
message overrides the default error message for assertion.

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

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

See Get BoundingBox for more similar examples.

Example use:

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

Comment >>

Getters & Assertions, line 1274

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.

Returned dictionaries have the following keys and their values "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 499

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

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.

Optionally matches with any sequence assertion operator.

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 counting
message overrides the default error message for assertion.
pseudo_element Pseudo element to match. Defaults to None. Pseudo elements are special css

Pseudo element is a css fuctionality to add styles. 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.

Comment >>

Getters & Assertions, line 1120

Get Table Cell Element

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

Arguments

NameDefaultType
tablerequiredstr
columnrequiredstr
rowrequiredstr

Returns

str

Tags

GetterPageContent

Documentation

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

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 descendant like <td> elements.

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

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

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

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 761

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

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

Get Text

Returns text attribute of the element found by selector.

Arguments

NameDefaultType
selectorrequiredstr
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

str

Tags

AssertionGetterPageContent

Documentation

Returns text attribute of the element found by selector.

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

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.

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

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

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.

Comment >>

Getters & Assertions, line 225

Get Title

Returns the title of the current page.

Arguments

NameDefaultType
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

str

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 189

Get Url

Returns the current URL.

Arguments

NameDefaultType
assertion_operator=NoneUnion
assertion_expected=NoneUnion
message=NoneUnion

Returns

str

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 117

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 counting
message overrides the default error message for assertion.

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

Example:

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

Comment >>

Getters & Assertions, line 710

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 page to load. If not defined will use the library default timeout.
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 the HTTP status code for the navigation request as integer or 0 if non received.

Comment >>

Browser Control, line 71

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 is a list of permissions to grant. Permissions can be one of the following: geolocation, notifications, camera, microphone,
origin The origin to grant permissions to, e.g. "https://example.com".

Example:

New ContextGrant Permissions    geolocation

Comment >>

Browser Control, line 610

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.

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

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

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

Example:

Handle Future Dialogs    action=acceptClick                    \#alerts

Comment >>

Interaction, line 848

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 locator 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 (Playwrights native). If playwright is used, width, style and color is ignored and only one highlighting can happen at the same time.

Keyword does not fail if selector resolves to multiple elements.

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 82

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 match matching selector. If there is none, wait until a matching element is attached to the DOM.
  • Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
  • Scroll the element into view if needed.
  • Use Mouse Move to hover over the center of the element, or the specified position.
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.
force Set to True to skip Playwright's [https://playwright.dev/docs/actionability Actionability checks].
*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.

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

Example:

Hover    h1Hover    h1    10   20    Alt

Comment >>

Interaction, line 495

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

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

The response is a Python dictionary with following attributes:

  • status <int> The status code of the response.
  • statusText <str> Status text corresponding to status, e.g OK or INTERNAL SERVER ERROR. This may not be available for all browser.
  • 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 range 200-299.

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

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

Comment >>

Network, line 59

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

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.press. Modifier keys DO NOT effect these methods. For testing modifier effects use single key presses with Keyboard Key press

Example:

Keyboard Input    insertText    0123456789

Comment >>

Interaction, line 1313

Keyboard Key

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

Arguments

NameDefaultType
actionrequiredKeyAction
keyrequiredstr

Tags

PageContentSetter

Documentation

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

Arguments Description
action Determine whether the key should be released (up), hold (down) or pressed once (press). down or up are useful for combinations i.e. with Shift.
key The key to be pressed. An example of valid keys are: F1 - F12, Digit0 - Digit9, KeyA - KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp , etc.

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

Example execution:

Keyboard Key    press    SKeyboard 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 1284

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 If set, Playwright will listen on the given path in addition to the main port. 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 494

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:

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

Comment >>

Web App State, line 124

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 for the assertion arguments. Defaults to None.

Example:

Local Storage Get Item    Key    ==    Value    My error${value} =    Local Storage 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:

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

Comment >>

Web App State, line 103

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:

Local Storage Set Item    Key    Value

Comment >>

Web App State, line 81

Merge Coverage Reports

Combines multiple raw coverage reports to 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 to 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 report format (default is "v8").

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

The output_folder argument is the folder where the combined report is saved. If folder does not exist, it is created. If folder exists, it's content is deleted before 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. 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.

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, Start Coverage keyword must be called with raw=True argument. Keyword should be used when there is a need to combine multiple reports to single report. For example, when tests are run in multiple pages, the example in 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 119

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 before action is executed.
button One of left, middle or up. Defaults to left.
clickCount Determine 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.

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    100 msMouse Button    click    ${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 1003

Mouse Move

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

Arguments

NameDefaultType
xrequiredfloat
yrequiredfloat
steps=1int

Tags

PageContentSetter

Documentation

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

Arguments Description
x & y Are 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 1244

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, which center is the start-point.
x & y Are relative coordinates to the center of the elements 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 1201

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 1264

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 to operate against the stock Google Chrome and Microsoft Edge browsers. 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.
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 configurations args and only uses the ones from args. If a list is given, then filters out the given default arguments. Dangerous option; use with care. Defaults to False.
proxy Network Proxy settings. Structure: {'server': <str>, 'bypass': <Optional[str]>, 'username': <Optional[str]>, 'password': <Optional[str]>}
reuse_existing If set to True, an existing browser instance, that matches the same arguments, will be reused. If no same configured Browser exist, a new one is started. Defaults to True.
slowMo Slows down Playwright operations by the specified amount of seconds or timedelta. 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 423

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 whithout any path.
colorScheme Emulates 'prefers-colors-scheme' media feature, supported values are 'light', 'dark', 'no-preference'.
defaultBrowserType If no browser is open and New Context opens a new browser with defaults, it now uses this setting. Very useful together with Get Device keyword.
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 forced-colors media feature, supported values are active and none.
geolocation A dictionary containing latitude and longitude or accuracy to emulate. If latitude or longitude is not specified, the device geolocation won't be overriden.
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 to a file. Must be path to file, example ${OUTPUT_DIR}/har.file. If not specified, the HAR is not recorded. Make sure to await context to close for the to be saved.
recordVideo Enables video recording for all pages into a folder. If not specified videos are not recorded. Make sure to close context for videos to be saved. Video is not support in remote browsers.
reduceMotion Emulates prefers-reduced-motion media feature, supported values are reduce, 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 stated created by the Save Storage State keyword. Must be full path to the file.
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 replaces 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}.tip. 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 enables 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. null disables the default viewport. If width and height is 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.

Comment >>

Browser, Context & Page, line 581

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 protocol, e.g. 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.

Comment >>

Browser, Context & Page, line 964

New Persistent Context

Open a new [https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context | 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

Open a new persistent context.

New Persistent Context does basically executes New Browser, New Context and New Page in one step with setting a profile at the same time.

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. More details for Chromium and Firefox. Note that Chromium's user data directory is the parent directory of the "Profile Path" seen at chrome://version. Pass an empty string to use a temporary directory instead.
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 699

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 75

Pause At

Advance the clock by jumping forward in time and pause the time.

Arguments

NameDefaultType
timerequireddatetime

Tags

ClockSetter

Documentation

Advance the clock by jumping forward in time and pause the time.

Argument Description
time The time to pause the clock at.

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

Example:

Set Time 2024-10-31 17:34:00 # Set the clock to a specific time
Do Something # Implement this in your keyword
Pause At 2024-10-31 18:34:00 # Pause the clock at a specific time
Check Something # Also this is implemented in your keyword
Resume Clock # Resume the clock
Do 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 press after each other. Using + to chain combine modifiers with a single keypress 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, 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 258

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.

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

Returns reference to the promised keyword.

kw Keyword that will work async on background.

Arguments Description
kw Keyword that will work async on 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 file from path has been uploaded.

Arguments

NameDefaultType
pathrequiredPathLike

Returns

Future

Tags

PageContentSetter

Documentation

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

Fails if the upload has not happened during timeout.

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

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 Upload File By Selector keyword.

Comment >>

Promises, line 268

Promise To Wait For Download

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

Arguments

NameDefaultType
saveAs=str
wait_for_finished=Truebool
download_timeout=NoneUnion

Returns

Future

Tags

BrowserControlWait

Documentation

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

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

With default filepath downloaded files are deleted when 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 download to finish, if wait_for_finished is set to True. If download is not finished during this time, keyword will be fail.

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

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.

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

Example usage:

New Context            acceptDownloads=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 140

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 when on the box in the page while recording.

Focus on the page and move 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 465

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 live time of this setting. Available values are Global, Suite or Test / Task. See Scope Settings 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. Taking a screenshot when something failed is a very useful feature, but notice that it can slow down the execution.

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

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

If Take Screenshot keyword, without arguments, is register as run on failure keyword, then filename argument default value is not used as screenshot file name. Instead, ${TEST NAME}_FAILURE_SCREENSHOT_{index} is used as file name. If there is need to use the filename argument default value, use robotframework-browser-screenshot-{index} as 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.
waitUntil When to consider operation succeeded, defaults to load.

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

Comment >>

Browser Control, line 583

Resume Clock

Resumes the clock.

Takes no arguments.

Tags

ClockSetter

Documentation

Resumes the clock.

Once keyword method is called, time resumes flowing, 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 headless.

Arguments Description
path Where pdf is saved, if not full path, will be saved 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 width or height options. Defaults to 'Letter'.
headerTemplate HTML template for the print header. See detailed explanation in below
height Paper height, accepts values labeled with units.
landscape Paper orientation. Defaults to false.
margin Defines pdf margins, see PdfMarging for more details
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 width and height or format options. 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 tagged (accessible) PDF. Defaults to false.
width Paper width, accepts values labeled with units.

headerTemplate and footerTemplate Should be valid HTML markup with following classes 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: > 1. Script tags inside templates are not evaluated. > 2. Page styles are not visible inside templates.

Returns the path to the saved PDF file.

More details can be found from Playwright pdf documentation

Example:

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

PDF, line 42

Save Storage State

Saves the current active context storage state to a file.

Takes no arguments.

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

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

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

Example:

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

Comment >>

Browser, Context & Page, line 1656

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 defining to scroll exactly one visible height down or up with -height. Be aware that some pages do lazy loading and load more content once you scroll down. The percentage of the current scrollable height is used and may change.
horizontal defines where to scroll horizontally. Works same as vertical but defines positive values for right and negative values for left. width defines to scroll exactly one visible range to the right.
behavior defines whether the scroll happens directly or it scrolls smoothly.

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

Comment >>

Interaction, line 607

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 that top or the bottom of the scroll area. < top bottom > Be aware that some pages do lazy loading and load more content once you scroll down. Bottom defines the current known bottom coordinate.
horizontal defines where to scroll horizontally. Works same as vertical but defines < left right > as start and end.
behavior defines whether the scroll happens directly or it scrolls smoothly.

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

Comment >>

Interaction, line 567

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 checkbox. See the Finding elements section for details about the selectors.

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

Does nothing if the element is already visible.

Comment >>

Interaction, line 647

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 list of options which keyword was able to select. The type of list item matches to attribute definition. Example if attribute equals to label returned list contains label values. Or in case of index it contains list of selected indexes.

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

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

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 714

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    myvalue3 SessionStorage ClearSessionStorage Get Item    mykey3    ==    ${None}

Comment >>

Web App State, line 227

SessionStorage Get Item

Get saved data from from 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 from 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

Example:

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

Comment >>

Web App State, line 146

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 206

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 185

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 key is the keyword name where formatters are applied. Dictionary value is a list of formatter which are applied. Formatters for a defined keyword are always overwritten. An empty list will clear all formatters for the keyword. If formatters is empty dictionary, then all formatters are cleared from all keywords.
scope Defines the lifetime of the formatter, possible values are Global, Suite and Test.

See type documentation of FormatterTypes 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 kind of spaces to single space and removes spaces from 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 98

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 Timeout of it is for current playwright context and for new contexts. Supports Robot Framework time format . Returns the previous value of the timeout.
scope Scope defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope Settings for more details.

Example:

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

Comment >>

Browser Control, line 367

Set Geolocation

Updated the correct Context's geolocation.

Arguments

NameDefaultType
latituderequiredfloat
longituderequiredfloat
accuracy=NoneUnion

Tags

BrowserControlSetter

Documentation

Updated the correct Context's geolocation.

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

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 552

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 element is highlighted on failure during a screenshot is taken. If False 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.

Example:

Set Highlight On Failure    True

Comment >> #TODO add real link

Browser Control, line 463

Set Offline

Toggles current Context's offline emulation.

Arguments

NameDefaultType
offline=Truebool

Tags

BrowserControlSetter

Documentation

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

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 perform waiting in 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}

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

Comment >>

Browser Control, line 399

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 disable 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 do 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 430

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 are searching elements will use Playwright strict mode. Keyword changes library strict mode value and keyword also return the previous strict mode value.
scope Scope defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope for more details.

Example:

${old_mode} =      Set Strict Mode    FalseGet Text           //input            # Does not fail if selector points to one or more 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.

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

The fixed makes Date.now and new Date() return fixed fake time at all times, keeps all the timers running.

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

The install fake timers 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 current Pages viewport size to specified dimensions.

Arguments

NameDefaultType
widthrequiredint
heightrequiredint

Tags

BrowserControlSetter

Documentation

Sets current Pages viewport size to specified dimensions.

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

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

Arguments Description
width Sets the width size.
height Sets the height size.

Comment >>

Browser Control, line 513

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.

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

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

Arguments Description
show If True banner is shown on page. If False banner is not shown on page. If None banner is shown on page only when running in presenter mode.
style Additional css styles to be applied to the banner. These styles are css settings and 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.

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 482

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
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 store 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 started when page is open and before any action is performed on the page. Coverage will be stored when calling Stop Coverage keyword or 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 to single report. Singel report can be created with rfbrowser coverage /path/to/basefolder/ /path/to/outputfolder/ command. Pleaee note that the raw argument is ignored if the config_file is defined. In this case user is responsible to also set the raw reporter in the config file. To see more details about combining coverage data, run: 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

Path

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. Returns the path to the folder where coverage reported.

Coverage, line 90

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 1286

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 1319

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.

New may timeout if no new pages exists before library timeout.

Example:

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

Comment >>

Browser, Context & Page, line 1372

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 custom path or filename. String {index} in filename will be replaced with a rolling number. Use this to not override filenames. If filename equals to UUID, then filename is created by Python uuid; https://docs.python.org/3/library/uuid.html. If filename equals to EMBED (case insensitive) or ${NONE}, then screenshot is embedded as Base64 image to the log.html. The image is saved temporally to the disk and warning is displayed if removing the temporary file fails. The ${OUTPUTDIR}/browser/ is removed at the first suite startup.
selector Take a screenshot of the element matched by selector. See the Finding elements section for details about the selectors. If not provided take a screenshot of current viewport.
crop Crops the taken screenshot to the given box. It takes same dictionary as returned from Get BoundingBox. Cropping only works on page screenshot, so if no selector is given.
disableAnimations When set to True, stops CSS animations, CSS transitions and Web Animations. Animations get different treatment depending on their duration: - finite animations are fast-forwarded to completion, so they'll fire transitionend event. - infinite animations are canceled to initial state, and then played over after the screenshot.
fileType png or jpeg Specify 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 overlayed with a pink box #FF00FF that completely covers its bounding box. 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 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 image in 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.
timeout Maximum time how long taking screenshot can last, defaults to library timeout. Supports Robot Framework time format, like 10s or 1 min, pass 0 to disable timeout. The default value can be changed by using the Set Browser Timeout keyword.

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 136

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 the New Context be set to true. This method taps the element by performing the following steps:

  • Wait for actionability checks on the element, unless 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, unless noWaitAfter option is set.
Arguments Description
selector Selector element to click. See the Finding elements section for details about the selectors.
*modifiers Modifier keys to press. Ensures that only these modifiers are pressed during the click, and then restores current modifiers back. If not specified, currently pressed modifiers are used. Modifiers can be specified in any order, and multiple modifiers can be specified. Valid modifier keys are Control, Alt, Shift and Meta.
force Whether to bypass the actionability checks. Defaults to false.
noWaitAfter Deprecated. This option has no effect. Actions that initiate navigations are waiting for these navigations 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.
position_x position_y A point to click relative to the top-left corner of element bounding-box. Only positive values within the bounding-box are allowed. If not specified, clicks to some visible point of the element.
trial When set, this method only performs the actionability checks and skips the action. Defaults to False.

Example:

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

Comment >>

Interaction, line 409

Type Secret

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

Arguments

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

Tags

PageContentSetter

Documentation

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

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

Arguments Description
selector Selector of the text field. See the Finding elements section for details about the selectors.
secret Environment variable name with % prefix or a local variable with $ prefix that has the secret text value. Variable names can be used with and without curly braces.
delay Delay between the single key strokes. It may be either a number or a Robot Framework time string. Time strings are fully explained in an appendix of Robot Framework User Guide. Defaults to 0 ms. Example: 50 ms
clear Set to false, if the field shall not be cleared before typing. Defaults to true.

This keyword does not log secret in Robot Framework logs, when keyword resolves the secret variable internally. When secret variable is prefixed with $, without the curly braces, library will resolve the corresponding Robot Framework variable.

If secret variable is prefixed with %, library will resolve corresponding environment variable. Example $Password` will resolve to ${Password} Robot Framework variable. Also %ENV_PWD will resolve to %{ENV_PWD} environment variable.

Using normal Robot Framework variables like ${password} will not work!

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

This keyword will also work with a give cryptographic cipher text, that has been encrypted by Crypto library. See Crypto Library 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 variablesType Secret    input#username_field    %username      # Keyword resolves $USERNAME/%USERNAME% variable value from environment variablesType Secret    input#username_field    ${username}    # Robot Framework resolves the variable value, but secrect can leak to Robot framework output files.

Comment >>

Interaction, line 136

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 shall not be cleared before typing. Defaults to true.

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

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

Example

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

Comment >>

Interaction, line 50

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 [https://playwright.dev/docs/actionability 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 691

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 upload is not done before library timeout. Therefor it may be necessary to increase the timeout with Set Browser Timeout. It is possible to upload multiple files or folder by defining additional paths or folders. in extra_paths.

If path is a directory, it will be uploaded all files from the directory. Subdirectories are not included. It is possible to upload files and directories with the same keyword.

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

if path is FileUploadBuffer dictionary, then 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 1361

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 one result if one promise waited. Otherwise returns an array of results. If one fails, then this keyword will fail.

See Promise To for more information about promises.

For general waiting of elements please see Implicit waiting.

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 227

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 prompt. Only valid if action argument equals accept. Defaults to empty string.
text Optional text to verify the dialogs text.
timeout Optional timeout in Robot Framework time format.

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

Example with returning text:

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

Example with text verify:

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

Comment >>

Interaction, line 877

Wait For Alerts

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

Arguments

NameDefaultType
actionsrequiredlist
prompt_inputsrequiredlist
textsrequiredlist
timeout=NoneUnion

Returns

list

Tags

PageContentWait

Documentation

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

Handles each alert/dialog with actions and optionally verifies the dialogs 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 prompt. Only valid if action argument equals accept. Defaults to empty string. IF input not preset, use None
texts List of optional text to verify the dialogs text. Use None if text verification should be disabled.
timeout Optional timeout in Robot Framework time format.

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

This keyword works in same way as Wait For Alert but can handle multiple alerts with one promise. Lie Wait For Alert keyword, this keyword must be called as argument to 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 927

Wait For All Promises

Waits for all promises to finish.

Takes no arguments.

Tags

Wait

Documentation

Waits for all promises to finish.

If one promises fails, then this keyword will fail.

Example:

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

Comment >>

Promises, line 253

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 Frameworks Wait Until Keywords Succeeds this keyword is more readable and easier to use but is limited to Browser libraries 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 238

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 polls the state of an element.

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

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

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 same state argument value.

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    //hi    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 given a selector a function is necessary, with an argument to capture the elementhandle. For example (element) => document.activeElement === element See the Finding elements section for details about the selectors.
polling Default polling value of "raf" polls in a callback for requestAnimationFrame. Any other value for polling will be parsed as a robot framework time for interval between polls.
timeout Uses default timeout of 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 162

Wait For Load State

Waits that the page reaches the required load state.

Arguments

NameDefaultType
state=loadPageLoadStates
timeout=NoneUnion

Tags

PageContentWait

Documentation

Waits that 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
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.

Example:

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

Waiting, line 307

Wait For Navigation

Waits until page has navigated to given url.

Arguments

NameDefaultType
urlrequiredUnion
timeout=NoneUnion
wait_until=loadPageLoadStates

Tags

HTTPWait

Documentation

Waits until page has navigated to given url.

Arguments Description
url Expected navigation target address either the exact match 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 operation succeeded, defaults to load. Events can be either: domcontentloaded - consider operation to be finished when the DOMContentLoaded event is fired. load - consider operation to be finished when the load event is fired. networkidle - consider operation to be finished when there are no network connections for at least 500 ms. commit - consider operation to be finished when network response is received and the document started loading.

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

Example:

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

Comment >>

Network, line 279

Wait For Request

Waits for request matching matcher to be made.

Arguments

NameDefaultType
matcher=Union
timeout=NoneUnion

Returns

Any

Tags

HTTPWait

Documentation

Waits for request matching matcher to be made.

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

See Wait For Response for more details.

CAUTION: Before Browser library 17.0.0, the matcher argument was always either a regex or JS function. But the regex did not needed 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 143

Wait For Response

Waits for response matching matcher and returns the response as robot dict.

Arguments

NameDefaultType
matcher=Union
timeout=NoneUnion

Returns

Union

Tags

HTTPWait

Documentation

Waits for response matching matcher and returns the response as robot dict.

The response, which is returned by this keyword, is a robot dictionary with following attributes:

  • status <int> The status code of the response.
  • statusText <str> Status text corresponding to status, e.g OK or INTERNAL SERVER ERROR. This may not be available for all browser.
  • 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 range 200-299.
  • request <dict> containing method <str>, headers <dict> and postData <dict> | <str>
  • url <str> url of the request.
Arguments Description
matcher Request URL matcher. Can be a string (Glob-Pattern), JavaScript RegExp (encapsulated in / with following flags) or JavaScript arrow-function that receives the Response object and returns a boolean. By default (with empty string) matches first available request. 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 needed 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. The following wildcards are supported:

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 request with url ending with /api/get/text. example: https://browser.fi/api/get/text

RegExp:

Regular Expressions are JavaScript regular expressions encapsulated in / with optional following 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 request 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 169

Wait Until Network Is Idle

DEPRECATED!! Use `Wait For Load State` instead. rfbrowser transform --wait-until-network-is-idle path/to/test command automatically transforms keyword to new format.

Arguments

NameDefaultType
timeout=NoneUnion

Tags

HTTPWait

Documentation

DEPRECATED!! Use Wait For Load State instead. rfbrowser transform --wait-until-network-is-idle path/to/test command automatically transforms keyword to new format.

If you have:

Wait Until Network Is Idle    timeout=3s

then change it to:

Wait For Load State    networkidle    timeout=3s

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

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

Arguments Description
timeout Timeout supports Robot Framework time format. Uses browser timeout if not set.

Example:

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

Comment >>

Network, line 255

Data types 77

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

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.

Accepted values

dictyaml

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.

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

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-colors-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
durationyestimedelta
widthyesstr
styleyesstr
coloryesstr

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

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.

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

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

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

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