Everything in the Browser library, generated from the library itself. Every argument type links to what it accepts, and every keyword links back from the types that use it.
Browser 20.4.020 modules83 argument types
Introduction
Generated from the library's Libdoc for 20.4.0. The original is at Browser.html.
Browser library is a browser automation library for Robot Framework.
This is the keyword documentation for Browser library. For installation, guides and everything else, see robotframework-browser.org. For more information about Robot Framework itself, see robotframework.org.
Playwright brings its own browser binaries, so no separate driver is needed. A browser starts headless unless New Browser's headless argument is set to False.
Engine
Ships in
chromium
Google Chrome, Microsoft Edge, Opera
firefox
Mozilla Firefox
webkit
Safari on macOS and iOS
The layers fill themselves in downwards: New Page with nothing open starts a browser and a context first, using defaults. Open Browser opens all three at once and is meant for experiments and debugging rather than for suites.
A context is the cheap unit of isolation — opening one is roughly a thousand times cheaper than starting a browser, so a clean session per test does not mean a new process. Context-level settings include viewport, geolocation, locale, colorScheme and httpCredentials; downloads are accepted unless acceptDownloads=False is given.
Each browser, context and page has an id. Get Browser Catalog returns everything currently open.
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.
Keywords that act on an element take a selector argument. A selector is one or more clauses, each naming a strategy, chained with >>.
Under strict mode a selector matching more than one element fails the keyword. It is on by default, changeable in the library importing or with Set Strict Mode, and each keyword's documentation states whether it applies.
An attribute engine is equivalent to the matching css attribute selector: data-test-id=foo is css=[data-test-id="foo"].
css:light is the only non-piercing engine still supported. All other locator, except xpath, pierce shadow DOM automatically.
Two filters narrow what a clause already matched. Filter order changes the result.
Filter
Selects
Example
nth
The nth match, zero based. 0 first, -1 last.
css=button >> nth=1
visible
Only visible, or only hidden, matches.
css=button >> visible=true
Playwright's CSS pseudo-classes (:has(), :has-text(), :nth-match()) and its layout selectors (:right-of(), :below()) are available inside a css clause. Which strategy to prefer, and the full list with examples: https://robotframework-browser.org/docs/concepts/selectors
Explicit and implicit strategy
A strategy is named with a strategy=value prefix. Spaces around the separator are ignored, so css=foo, css= foo and css = foo are the same.
Without a prefix the strategy is inferred:
Selector starts with
Read as
Example
// or ..
xpath
//span/button is xpath=//span/button
" or '
text, exact
"Login" is text="Login"
anything else
css
span > button is css=span > button
Because # starts a comment in Robot Framework data, an id selector must be escaped as \#id.
css follows the CSS selector specification and xpath the XPath specification; neither is re-documented here.
Text matching
The text engine matches a text node, and the value of button and submit inputs. In keywords that insert text it also matches a field by its label.
Form
Matches
text=Login
Substring, case-insensitive, leading and trailing whitespace ignored.
text="Login "
Exact: case, whitespace and all. Escape a quote as \".
text=/^Hi .*!$/i
JavaScript-style regular expression with flags: e.g. i for case-insensitive.
Chaining
Clauses are separated by >> and each searches inside the result of the previous one. The chain returns what the last clause matched; prefix a clause with * to return that one instead. A value containing >> must be quoted, as in text="some >> text".
Click css=.checkout >> text=ConfirmGet Element *css=article >> text=Hello # returns the article
iFrames
A chain does not cross a frame boundary. >>> combines a selector for the frame element with a selector inside it; the clause immediately before >>> must select the frame itself.
Click id=iframe >>> id=btn
For several keywords inside one frame, set a prefix with Set Selector Prefix.
Shadow DOM
All engines, except css:light and xpath, pierce open shadow roots automatically: every descendant combinator, including the implicit one at the start of a selector, crosses any number of them. Light DOM is searched first, then open shadow roots, in document order. Closed shadow roots and iframes are never entered.
Get Element returns a selector string for what it matched, and Get Elements returns a list of them. They are ordinary selectors, so they go in the first clause of another selector, chained with >>:
${ref}= Get Element .some_class Click ${ref} >> .some_child Click ${ref} >> .other_child
Clauses after the reference are relative to it. Because the value is a selector rather than a captured DOM node, it is resolved from the page again on every use. A reference works like any other first clause, >>> included: if it points at an iframe, ${ref} >>> h1 crosses into it.
Assertions
Keywords taking assertion_operator <AssertionOperator> and assertion_expected can assert on the value they return, and still return it. An assertion retries until it passes or retry_assertions_for expires; see Importing for that setting, which defaults to 1 second.
Currently supported assertion operators are:
Operator
Alternative Operators
Description
Validate Equivalent
==
equal, equals, should be
Checks if returned value is equal to expected value.
value == expected
!=
inequal, should not be
Checks if returned value is not equal to expected value.
value != expected
>
greater than
Checks if returned value is greater than expected value.
value > expected
>=
Checks if returned value is greater than or equal to expected value.
value >= expected
<
less than
Checks if returned value is less than expected value.
value < expected
<=
Checks if returned value is less than or equal to expected value.
value <= expected
*=
contains
Checks if returned value contains expected value as substring.
expected in value
not contains
Checks if returned value does not contain expected value as substring.
expected in value
^=
should start with, starts
Checks if returned value starts with expected value.
re.search(f"^{expected}", value)
$=
should end with, ends
Checks if returned value ends with expected value.
re.search(f"{expected}$", value)
matches
Checks if given RegEx matches minimum once in returned value.
re.search(expected, value)
validate
Checks if given Python expression evaluates to True.
evaluate
then
When using this operator, the keyword does return the evaluated Python expression.
There are three different possibilities what keyword returns when matches operator is used: string, tuple or dictionary. What keyword returns depends on how the RegEx is formed. If RegEx does not contain group(s), then keyword will return the string without modifications. If RegEx contains groups, meaning (...), then keyword will return a tuple. Each tuple item contains the text which is matched by the group. If there is group and group has a name, (?P<name>...) syntax, then keyword returns a dictionary. In this case dictionary key is the group name and value contains the matched text. If there mix of groups and groups with names, then tuple is returned.
Currently supported formatters for assertions are:
Formatter
Description
normalize spaces
Substitutes multiple spaces to single space from the value
strip
Removes spaces from the beginning and end of the value
case insensitive
Converts value to lower case before comparing
apply to expected
Applies rules also for the expected value
Formatters are applied to the value before assertion is performed and keywords returns a value where rule is applied. Formatter is only applied to the value which keyword returns and not all rules are valid for all assertion operators. If apply to expected formatter is defined, then formatters are then formatter are also applied to expected value.
Expected values are generally used as given, so they must already have the type returned by the keyword. Keywords returning numbers are an exception and convert the expected value.
Examples:
Get Text returns a string even when it looks like a number
Comparing strings with < or > compares code points character by character and stops at the first difference; length is never considered. Example: A < Z, Z < a, ac < dc, 'abcde' < 'abd'.
validate takes a Python expression over value. then and evaluate do not assert: they return the result of an expression over value.
Get Text h1 validate value.startswith("Welcome")${id}= Get Property a#link href then value.split("/")[-1]
A failing assertion has a default message, replaceable with message. It accepts the format fields {value}, {expected}, {value_type} and {expected_type}.
Browser library and Playwright have many mechanisms to help in waiting for elements. Playwright will auto-wait before performing actions on elements. Please see Auto-waiting on Playwright documentation for more information.
On top of Playwright auto-waiting Browser assertions will wait and retry for specified time before failing any Assertions. Time is specified in Browser library initialization with retry_assertions_for.
Browser library also includes explicit waiting keywords such as Wait for Elements State if more control for waiting is needed.
Experimental: Re-using same node process
The Node.js side can be started as a standalone process and shared by every Browser library running on the same machine, instead of each one starting its own. This can speed up parallel runs. Start it from the directory where the Browser package is installed with ` PLAYWRIGHT_BROWSERS_PATH=0 node Browser/wrapper/index.js HOST PORT ` , for example ... index.js 127.0.0.1 12345. Both arguments are required: the script reads the host first and exits with No port defined if only one is given. Point runs at it with the playwright_process_port import parameter or the ROBOT_FRAMEWORK_BROWSER_NODE_PORT environment variable, for example ROBOT_FRAMEWORK_BROWSER_NODE_PORT=PORT pabot ...
Some keywords which manipulates library settings have a scope argument. With that scope argument one can set the "live time" of that setting. Available Scopes are: Global, Suite and `Test/Task See Scope`. Is a scope finished, this scoped setting, like timeout, will no longer be used.
Live Times:
A Global scope will live forever until it is overwritten by another Global scope. Or locally temporarily overridden by a more narrow scope.
A Suite scope will locally override the Global scope and live until the end of the Suite within it is set, or if it is overwritten by a later setting with Global or same scope. Children suite does inherit the setting from the parent suite but also may have its own local Suite setting that then will be inherited to its children suites.
A Test or Task scope will be inherited from its parent suite but when set, lives until the end of that particular test or task.
A new set higher order scope will always remove the lower order scope which may be in charge. So the setting of a Suite scope from a test, will set that scope to the robot file suite where that test is and removes the Test scope that may have been in place.
Using Browser from Python
Browser keywords can be called directly from Python, from your own Robot Framework library. Arguments convert the same way Robot Framework converts them, so browser.click("//button", "middle") works, and a Python None is passed through unchanged. Robot Framework's own features do not all follow: Automatic page and context closing and Scope Setting need Browser's listener to be registered, and run_on_failure never applies to a keyword your library calls from Python.
Keyword names and their documentation can be translated. Install a Python package whose name starts with robotframework_browser_translation and set the language import parameter to the language that the package declares; Browser discovers it on the module search path through the Python plugin API.
A template for a new translation, containing every keyword in the correct format, is produced by rfbrowser translation /path/to/translation.json. Keywords coming from library plugins and JavaScript extensions can be included with the --plugings and --jsextension arguments.
These environment variables modify the behaviour of the library. Two of them are development features and must not be set in production; they are listed here so that nobody uses them by accident.
Environment variable
Description
ROBOT_FRAMEWORK_BROWSER_NODE_PORT
Port number for connecting to an existing node process. This is an alternative to playwright_process_port import argument.
ROBOT_FRAMEWORK_BROWSER_NODE_COVERAGE
If set to 1, will collect code coverage for the node process. This must not be used in production environments and is not supported on Windows.
ROBOT_FRAMEWORK_BROWSER_NODE_DEBUG_OPTIONS
Debug options for the node process. This is a comma-separated list of arguments, for example --inspect. This must not be used in production environments.
Adds a cookie to the currently active browser context.
Arguments
Description
name
Name of the cookie.
value
Given value for the cookie.
url
Given url for the cookie. Defaults to None. Either url or the domain / path pair must be set, but not both.
domain
Given domain for the cookie. Defaults to None. Either url or the domain / path pair must be set, but not both.
path
Given path for the cookie. Defaults to None. Either url or the domain / path pair must be set, but not both.
expires
Given expiry for the cookie. Can be a date, a unix time or a datetime object. Supports the same formats as the DateTime library or an epoch timestamp. Example: 2027-09-28 16:21:35
httpOnly
Sets the httpOnly token.
secure
Sets the secure token.
sameSite
Sets the sameSite mode. Can be Strict, Lax or None.
Example:
Add Cookie foo bar http://address.com/path/to/site # Using url argument.Add Cookie foo bar domain=example.com path=/foo/bar # Using domain and path arguments.Add Cookie foo bar http://address.com/path/to/site expires=2027-09-28 16:21:35 # Expires as timestamp.Add Cookie foo bar http://address.com/path/to/site expires=1822137695 # Expires as epoch seconds.
Add a handler function which will activate when selector is visible and click.
The handler will click the element indicated by click_selector.
When testing a web page, sometimes unexpected overlays, for example an "Accept Cookies" dialog, might appear and block the interaction with the page, like the Click keyword. These overlays can be problematic to handle, because they might appear randomly in the page. This keyword allows to create an automatic method, which will close those overlays by clicking the element indicated by click_selector. The handler is activated when the element indicated by selector is visible. For further information, see Playwright's addLocatorHandler method.
Arguments
Description
selector
Is the selector to the element which indicates that the locator handler should be called.
noWaitAfter
Defaults to True, which means that the overlay may stay visible after the handler has run. If set to False, Playwright waits until the overlay becomes hidden, and only then the library continues with the action/assertion that triggered the handler.
times
Is how many times the locator handler is called. None, the default, means unlimited.
click_selector
Is the selector to the element to be clicked.
click_clickCount
Is the number of times to click the element. Defaults to 1.
click_delay
Time to wait between mousedown and mouseup in milliseconds. Defaults to 0.
click_force
Whether to bypass checks and dispatch the event directly. Defaults to false.
The arguments click_selector, click_clickCount, click_delay and click_force correspond to the arguments of the Click With Options keyword, but click_delay is given as a plain number of milliseconds. The selector, noWaitAfter and times are for the locator handler. The handler is tied to the active page, if there is need to add handler to another page, this keyword needs to be called separately for each page. If the times argument is set to a positive value, the locator handler is removed after the handler has been called the specified number of times.
Example add locator handler to click button with id="ButtonInOverlay" when id=Overlay is visible:
New Page ${URL}Add Locator Handler Click id=Overlay id=ButtonInOverlay # Add locator handler to pageType Text id:username user # If element with id=Overlay appears, the handler will click the button id=ButtonInOverlayType Text id:password password # Or if overlay is visible here, then handler is called hereClick id:loginRemove Locator Handler id=Overlay # Removes the locator handler from page
Add a handler function which will activate when selector is visible and performs handler specification.
When the element indicated by selector is visible, the handler will perform the actions specified in the handler_spec.
Arguments
Description
selector
Is the selector to the element which indicates that the locator handler should be called.
handler_spec
Is a list of dictionaries which defines the actions to be performed.
noWaitAfter
Defaults to True, which means that the overlay may stay visible after the handler has run. If set to False, Playwright waits until the overlay becomes hidden, and only then the library continues with the action/assertion that triggered the handler.
times
Is how many times the locator handler is called. None, the default, means unlimited.
The handler_spec is a list of dictionaries, where each dictionary defines one action. The dictionary must contain the key action which defines the action to be performed. The action can be one of the following: click, fill, check and uncheck. Action is also case insensitive. The dictionary must also contain the key selector which defines the element to be interacted with. The fill action must also contain the key value which defines the value to be filled in the element. For the other actions the key value must not be defined. Additional keys are passed to the action as keyword arguments. For example for the click action refer to Playwright's documentation to see which options are possible.
The selectors in the handler_spec are not resolved in strict mode. If a selector matches more than one element, the first matching element is used. If an action in the handler fails, the error is only logged on the Browser library node side and the keyword which triggered the handler does not fail because of it.
The selector, noWaitAfter and times are for the locator handler method. The handler is tied to the active page, if there is need to add handler to another page, this keyword needs to be called separately for each page. If the times argument is set to a positive value, the locator handler is removed after the handler has been called the specified number of times.
Running the handler will alter your page state mid-test. For example it will change the currently focused element and move the mouse. Make sure that keywords that run after the handler are self-contained and do not rely on the focus and mouse state being unchanged.
Please note that the automatic argument conversion is not done for the handler_spec dictionary. This is because Robot Framework does not convert values inside the dictionary that are actually arguments to a separate Playwright API call. Therefore the user is responsible for converting the values to the correct type. For example if a timeout is needed, the value must be converted to a number on the Robot Framework test data side.
Example adds locator handler to fill input id=overlayInput with value "Hello" and click element id=OverlayCloseButton when id=Overlay is visible:
New Page ${URL}VAR &{handler_spec_fill}... action=Fill... selector=id=overlayInput... value=HelloVAR &{handler_spec_click}... action=click... selector=id=OverlayCloseButtonAdd Locator Handler Custom... id=overlay... [${handler_spec_fill}, ${handler_spec_click}]Type Text id:username user # If element with id=overlay appears, the handler fills id=overlayInput and clicks id=OverlayCloseButtonType Text id:password password # Or if overlay is visible here, then handler is called hereClick id:login
Example with click and different options and types:
VAR &{handler_spec}... action=CLICK # Action is case insensitive... selector=id=OverlayCloseButton... button=left... clickCount=${1}... delay=${0.1}... force=${True}Add Locator Handler Custom id=overlay [${handler_spec}]
The keyword can only handle click, fill, check and uncheck Playwright API calls. If there is a need for more complex interactions, it is recommended to create a custom js extension to handle the interactions.
Example:
async function customLocatorHandler(locator, pageLocator, clickLocator, page) { console.log("Adding custom locator handler for: " + locator); const pageLocator = page.locator(locator).first(); await page.addLocatorHandler( pageLocator, async () => { console.log("Handling custom locator: " + clickLocator); // More complex interactions can be added here await page.locator(clickLocator).click(); } );}exports.__esModule = true;exports.customLocatorHandler = customLocatorHandler;
Simulates mouse click on the element found by selector.
This keyword clicks an element matching selector by performing the following steps:
Find an element matching the selector. If there is none, wait until a matching element is attached to the DOM.
Wait for actionability checks on the matched element, unless the force option is set. If the element is detached during the checks, the whole action is retried.
Scroll the element into view if needed.
Use Mouse Button to click in the center of the element, or the specified position.
Wait for initiated navigation to either succeed or fail, unless the noWaitAfter option is set.
Arguments
Description
selector
Selector element to click. See the Finding elements section for details about the selectors.
button
Mouse button to click with. One of left, middle or right. Defaults to left.
*modifiers
Modifier keys to press. Ensures that only these modifiers are pressed during the click, and then restores current modifiers back. If not specified, currently pressed modifiers are used. Modifiers can be specified in any order, and multiple modifiers can be specified. Valid modifier keys are Alt, Control, ControlOrMeta, Meta and Shift. Due to the fact that the argument *modifiers is a positional only argument, all preceding keyword arguments have to be specified as positional arguments before *modifiers.
clickCount
How many times the button is clicked. Defaults to 1.
delay
Time to wait between mouse-down and mouse-up. Defaults to no delay.
position_xposition_y
A point to click relative to the top-left corner of element bounding-box. Only positive values within the bounding-box are allowed. Both values must be given, otherwise the position is ignored. If not specified, clicks to some visible point of the element.
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
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
Active context is set to the context that was active before this one. Closes pages belonging to this context. See Browser, Context and Page for more information about Context and related concepts.
Argument
Description
context
Context to close. CURRENT selects the active context. ALL selects all contexts. When a context id is provided, that context is closed.
browser
Browser in which contexts are closed. CURRENT selects the active browser. ALL selects all browsers. When a browser id is provided, contexts of that browser are closed. The browsers themselves are not closed.
save_trace
If set to False, the trace of this context is not saved, even if it was enabled by New Context. Defaults to True.
Example:
Close Context # Closes the current context of the current browserClose Context CURRENT CURRENT # Closes the current context of the current browserClose Context ALL CURRENT # Closes all contexts of the current browserClose Context ALL ALL # Closes all contexts of all browsers
Defaults to current for all three. Active page is set to the page that was active before this one. See Browser, Context and Page for more information about Page and related concepts.
runBeforeUnload defines where to run the before unload page handlers. Defaults to false.
Argument
Description
page
Page to close. CURRENT selects the active page. ALL selects all pages. When a page id is provided, that page is closed.
context
Context in which pages are closed. CURRENT selects the active context. ALL selects all contexts. When a context id is provided, pages of that context are closed. The contexts themselves are not closed.
browser
Browser in which pages are closed. CURRENT selects the active browser. ALL selects all browsers. When a browser id is provided, pages of that browser are closed. The browsers themselves are not closed.
If a page id is given, the context and browser arguments are ignored and the page is searched from all open browsers. Likewise, if a context id is given, the browser argument is ignored.
Returns a list of dictionaries containing id, errors and console messages from the page.
Example:
Close Page # Closes current page, within the current context and browserClose Page CURRENT CURRENT CURRENT # Closes current page, within the current context and browserClose Page ALL ALL ALL # Closes all pages, within all contexts and browsers
Returns a stable identifier for the connected browser.
Argument
Description
wsEndpoint
Address to connect to. Either ws:// or http:// if cdp is used.
browser
Opens the specified browser. Defaults to chromium.
use_cdp
Connect to browser via Chrome DevTools Protocol. Defaults to False. Works only with Chromium based browsers.
timeout
Maximum time in Robot Framework time format to wait for the connection to be established. Defaults to 30 seconds. The timeout can not be disabled; 0 also means 30 seconds.
To connect to a browser via Chrome DevTools Protocol, the browser must be started with this protocol enabled. This is typically done by starting a Chrome browser with the argument --remote-debugging-port=9222 or similar. When the browser is running with activated CDP, it is possible to connect to it either with websockets (ws://) or via HTTP (http://). The HTTP connection can be used when use_cdp is set to True. A typical address for a CDP connection is http://127.0.0.1:9222.
Web crawler is a tool to go through all the pages on a specific URL domain. This happens by finding all links going to the same site and opening those. Links pointing to another scheme or host are ignored, as are download links.
Web crawler is a tool to go through all the pages on a specific URL domain. This happens by finding all links going to the same site and opening those. Links pointing to another scheme or host are ignored, as are download links.
Returns the list of crawled urls. The order of the returned urls is not guaranteed to be the order in which the pages were crawled.
Arguments
Description
url
is the page to start crawling from. If it is given, a New Page is opened with that url. If it is not given, crawling starts from the url of the current page.
page_crawl_keyword
is the keyword that will be executed on every page. It is run without arguments. By default it will take a screenshot on every page.
max_number_of_page_to_crawl
is the upper limit of pages to crawl. Crawling will stop when this number of pages has been crawled.
max_depth_to_crawl
is the upper limit of consecutive links followed from the start page. The start page has depth 0 and links deeper than this limit are not followed.
Will always https://playwright.dev/docs/api/class-credentials#credentials-create and https://playwright.dev/docs/api/class-credentials#credentials-install the credential, even if the optional parameters are not provided. In this case Playwright will autogenerate the missing values.
The credential is created in the currently active context and it is used by all pages that are created from that context. There must be an open context, otherwise the keyword fails.
Arguments
Description
rpId
Relying party id (typically the site's effective domain).
id_
Base64url-encoded credential id. Auto-generated if omitted.
privateKey
Base64url-encoded PKCS#8 (DER) private key. Auto-generated if omitted.
publicKey
Base64url-encoded SPKI (DER) public key. Auto-generated if omitted.
userHandle
Base64url-encoded user handle. Auto-generated if omitted.
Because privateKey and publicKey are sensitive information, it is recommended to wrap their values in the Secret type. The Secret type requires Robot Framework 7.4 or newer. If you are using Robot Framework 7.3 or older, the keyword supports resolving privateKey and publicKey from Robot Framework variables and environment variables in the following ways. The keyword resolves the value from a Robot Framework variable internally, when the variable is prefixed with $, without the curly braces. Example: $publicKey will resolve to the ${publicKey} Robot Framework variable.
If the privateKey or publicKey value is prefixed with %, the library will resolve the corresponding environment variable. Example: %PUBLICKEY will resolve to the %{PUBLICKEY} environment variable.
Plain values are not accepted. If the given privateKey or publicKey is not a Secret and does not resolve to another value, the keyword fails with an error stating that direct assignment of values or variables is not allowed.
Example:
New Context${credentials} = Get Credentials # This is a helper keyword that returns a dictionary with the required credential parameters.Create Credential... rpId=${DOMAIN_NAME}... id_=${credentials["id"]}... privateKey=${credentials["privateKey"]} # This should be a Secret type or a string starting with $ which resolves to a Robot Framework variable.... publicKey=${credentials["publicKey"]} # This should be a Secret type or a string starting with $ which resolves to a Robot Framework variable.... userHandle=${credentials["userHandle"]}New Page ${SUT_URL}Click id=loginGet Text id=status == Success
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.
When wait_for_finished is False, the returned dictionary has an empty saveAs, the state is in_progress and downloadID contains the id of the download. The download can then be followed with the Get Download State keyword, which also saves the file to saveAs when the download is finished.
If the download should be started by an interaction with an element on the page, Promise To Wait For Download keyword may be a better choice.
The keyword New Browser has a downloadsPath setting which can be used to set the default download directory. If saveAs is set to a relative path, the file will be saved relative to the browser's downloadsPath setting or if that is not set, relative to the Playwright's working directory. If saveAs is set to an absolute path, the file will be saved to that absolute path independent of downloadsPath.
To enable downloads context's acceptDownloads needs to be true, otherwise the keyword fails. This keyword requires that there is currently an open page and that the page has been navigated to an url, downloading from about:blank fails. The download is done by a fetch call inside the page and therefore it uses the current page's local state (cookies, sessionstorage, localstorage) to avoid authentication problems. Because of that, a relative url is resolved against the current page url and the page's cross-origin restrictions apply.
Example:
${file_object}= Download ${url}${actual_size}= Get File Size ${file_object.saveAs}
Example 2:
${href}= Get Property text="Download File" hrefDownload ${href} saveAs=${OUTPUT DIR}/downloads/downloaded_file.txtFile Should Exist ${OUTPUT DIR}/downloads/downloaded_file.txt
Executes a Drag&Drop operation from the element selected by selector_from to the element selected by selector_to.
Arguments
Description
selector_from
Identifies the element whose center is the start-point.
selector_to
Identifies the element whose center is the end-point.
steps
Defines how many intermediate mouse move events are sent. Often it is necessary to send more than one intermediate event to get the desired result. Defaults to 1.
See the Finding elements section for details about the selectors.
First it moves the mouse to the start-point, then presses the left mouse button, then moves to the end-point in specified number of steps, then releases the mouse button.
Start- and end-point are defined by the center of the elements' bounding box.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Executes a Drag&Drop operation from a coordinate to another coordinate.
First it moves the mouse to the start-point, then presses the left mouse button, then moves to the end-point in specified number of steps, then releases the mouse button.
Start- and end-point are defined by x and y coordinates relative to the top left corner of the pages viewport.
Arguments
Description
from_x & from_y
Identify the start-point on page.
to_x & to_y
Identify the end-point.
steps
Defines how many intermediate mouse move events are sent. Often it is necessary to send more than one intermediate event to get the desired result. Defaults to 1.
Example:
Drag And Drop By Coordinates... from_x=30 from_y=30... to_x=10 to_y=10 steps=20
Executes a Drag&Drop operation from the element selected by selector_from to coordinates relative to the center of that element.
This keyword can be handy to simulate swipe actions.
Arguments
Description
selector_from
Identifies the element whose center is the start-point.
x & y
Identify the end-point, which is relative to the start-point.
steps
Defines how many intermediate mouse move events are sent. Often it is necessary to send more than one intermediate event to get the desired result. Defaults to 1.
See the Finding elements section for details about the selectors.
First it moves the mouse to the start-point (center of the bounding box), then presses the left mouse button, then moves to the relative position with the given intermediate steps, then releases the mouse button.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Example
Drag And Drop Relative To "Circle" -20 0 # Slides the element 20 pixels to the left
It changes the CSS media type through the media argument, and/or the prefers-color-scheme media feature, using the colorScheme argument. This is useful to render the page in the correct format before using the Save Page As Pdf keyword.
Arguments
Description
colorScheme
Emulates the prefers-color-scheme media feature, supported values are light and dark. Passing null disables color scheme emulation. no-preference is deprecated.
forcedColors
Emulates the forced-colors media feature, supported values are active and none. Passing null disables forced colors emulation.
media
Changes the CSS media type of the page. The only allowed values are screen, print and null. Passing null disables CSS media emulation.
reducedMotion
Emulates the prefers-reduced-motion media feature, supported values are reduce and no-preference. Passing null disables reduced motion emulation.
Arguments which are left to their default value are not sent to Playwright at all and therefore the corresponding emulation is left unchanged.
Executes the given JavaScript in the browser page.
The JavaScript is evaluated in the context of the page, not in the Node process of the library. Therefore browser globals like window and document are available, but Robot Framework variables and Python objects are not. Only arg and the resolved element(s) are passed into the page.
Arguments
Description
selector
Selector to resolve and pass to the JavaScript function. This will be the first argument the function receives if not ${None}. selector is optional and can be omitted. If given a selector, a function is necessary, with an argument to capture the element. For example (element) => document.activeElement === element See the Finding elements section for details about the selectors.
*function
A valid javascript function or a javascript function body. These arguments can be used to write readable multiline JavaScript.
arg
an additional argument that can be handed over to the JavaScript function. It is the second argument of the function when a selector is given, otherwise the first one. This argument must be JSON serializable. ElementHandles are not supported.
all_elements
defines if only the single element found by selector is handed over to the function or if set to True all found elements are handed over as array.
The value returned by the JavaScript is transferred as JSON and must therefore be JSON serializable. DOM nodes and other non serializable objects can not be returned. If the JavaScript does not return anything, the keyword returns an empty string.
Example with all_elements=True:
${texts}= Evaluate JavaScript button ... (elements, arg) => { ... let text = [] ... for (e of elements) { ... console.log(e.innerText) ... text.push(e.innerText) ... } ... text.push(arg) ... return text ... } ... all_elements=True ... arg=Just another Text
Keyword uses strict mode only if all_elements is False. See Finding elements for more details about strict mode.
Fills the given secret into the text field found by selector.
Arguments
Description
selector
Selector of the text field. See the Finding elements section for details about the selectors.
secret
The secret string that should be filled into the text field. Supports Robot Framework 7.4 Secret type as normal variable (with curly braces). Also environment variable name with % prefix or a local variable with $ prefix that has the secret text value (without curly braces).
This keyword does not log the secret in Robot Framework logs, but if Playwright debug logs are enabled, the secret will be visible as plain text in the Playwright debug logs, regardless of the Robot Framework log level or how secret is resolved.
This keyword supports Robot Framework 7.4 Secret variable type, which is the recommended way if you are using Robot Framework 7.4 or newer.
For older Robot Framework versions the keyword supports resolving secrets from environment variables and Robot Framework variables in the following ways. The keyword resolves the secret from a Robot Framework variable internally, when the secret variable is prefixed with $, without the curly braces. Example: $Password will resolve to the ${Password} Robot Framework variable.
If the secret variable is prefixed with %, the library will resolve the corresponding environment variable. Example: %ENV_PWD will resolve to the %{ENV_PWD} environment variable.
Using normal Robot Framework variables like ${password}, which are not Secret type variables, will not work!
Normal plain text will not work. If you want to use plain text, use the Fill Text keyword instead.
This keyword also works with a cryptographic cipher text that has been encrypted by CryptoLibrary. See CryptoLibrary for more details.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Fill Secret input#username_field ${username} # Keyword resolves variable value from Robot Framework Secret type variablesFill Secret input#username_field $username # Keyword resolves variable value from Robot Framework variablesFill Secret input#username_field %username # Keyword resolves variable value from environment variables
Clears and fills the given txt into the text field found by selector.
This keyword waits for an element matching the selector to appear, waits for actionability checks, focuses the element, fills it and triggers an input event after filling.
If the element matching the selector is not an <input>, <textarea> or [contenteditable] element, this keyword fails. Note that you can pass an empty string as txt to clear the input field.
Arguments
Description
selector
Selector of the text field. See the Finding elements section for details about the selectors.
Selector of the element. See the Finding elements section for details about the selectors.
Keyword uses strict mode, see Finding elements for more details about strict mode.
If there is no element matching the selector, the keyword waits until a matching element appears in the DOM. It fails if the element does not appear within the library timeout, which is 10 seconds by default and can be changed with Set Browser Timeout.
Returns the aria snapshot of the element found by selector. See AriaSnapshotReturnType for more details and examples.
Arguments
Description
selector
Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.
return_type
Defines the return type. Possible values are yaml (default), dict and parsed. If yaml is selected, the returned value is a string in YAML format. If dict is selected, the returned value is a dictionary. If parsed is selected, the returned value is a tree of node dictionaries.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the state
message
overrides the default error message for assertion.
mode
Defines the snapshot mode. Possible values are default (default) and ai. See AriaSnapshotMode for more details.
depth
Limits the snapshot to the given number of tree levels. Must be a positive integer. Defaults to None, which does not limit the depth.
boxes
If True, the bounding box of each element is appended to its line as [box=x,y,width,height]. Coordinates are relative to the viewport, in CSS pixels. Defaults to False.
Keyword uses strict mode, see Finding elements for more details about strict mode.
With mode=ai the snapshot is optimized for AI consumption: it contains element references like [ref=e2] and the content of iframes inside the element. It also does not wait for a matching element, but fails immediately when no element matches, instead of failing with a timeout like the default mode does.
With return_type=dict the YAML returned by Playwright is loaded as is. The [ref=...] and [box=...] annotations are therefore part of the dictionary keys, not separate entries. Use return_type=parsed to get them as separate values of each node.
Optionally asserts that the snapshot matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
Example:
${aria} = Get Aria Snapshot id=main # returns YAML stringLog Many ${aria}${aria_dict} = Get Aria Snapshot id=main dict # returns dictionaryLog Many ${aria_dict}
Returns the HTML attribute of the element found by selector.
Arguments
Description
selector
Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.
attribute
Requested attribute name.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the state
message
overrides the default error message for assertion.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Optionally asserts that the attribute value matches the expected value. See Assertions for further details for the assertion arguments. By default assertion is not done.
When an attribute is selected that is not present and no assertion operator is set, the keyword fails. If an assertion operator is set and the attribute is not present, the returned value is None. This can be used to check the presence or the absence of an attribute.
Returns all HTML attribute names of an element as a list.
Arguments
Description
selector
Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.
assertion_operator
See Assertions for further details. Defaults to None.
*assertion_expected
Expected value for the state
message
overrides the default error message for assertion.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Optionally asserts that the attribute names match the expected values. See Assertions for further details for the assertion arguments. By default assertion is not done.
Available assertions:
== , != and contains / *= can work with multiple values
validate and evaluate only accept one single expected value
Other operators are not allowed.
Example:
Get Attribute Names [name="readonly_input"] == type name value readonly # Has exactly these attribute names.Get Attribute Names [name="readonly_input"] contains disabled # Contains at least this attribute name.
Gets elements size and location as an object {x: float, y: float, width: float, height: float}.
Alternatively you can select a single attribute of the bounding box by setting the key argument.
If an element is hidden and has no bounding box, the keyword will fail. Depending on the method used to make an element invisible, an element might still have a bounding box which can be retrieved. To allow also hidden elements without a bounding box, set allow_hidden to True, which results in a return value of None in case of no bounding box.
Arguments
Description
selector
Selector from which the bounding box shall be retrieved. See the Finding elements section for details about the selectors.
key
Optionally filters the returned values. If keys is set to ALL (default) it will return the BoundingBox as Dictionary, otherwise it will just return the single value selected by the key. Note: If a single value is retrieved, an assertion does not need a validate combined with a cast of value.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the assertion
message
overrides the default error message for assertion.
allow_hidden
(named only) If True, hidden elements are not causing a failure and will return None. Otherwise a hidden element will fail. Defaults to False.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Optionally asserts that the value matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
Example use:
${bounding_box}= Get BoundingBox id=element # unfilteredLog ${bounding_box} # {'x': 559.09375, 'y': 75.5, 'width': 188.796875, 'height': 18}${x}= Get BoundingBox id=element x # filteredLog X: ${x} # X: 559.09375# Assertions:Get BoundingBox id=element width > 180Get BoundingBox id=element ALL validate value['x'] > value['y']*2
Returns the state of the checkbox found by selector.
Optionally asserts that the state matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
Arguments
Description
selector
Selector which shall be examined. See the Finding elements section for details about the selectors.
assertion_operator
== and != and equivalent are allowed on boolean values. Other operators are not accepted.
assertion_expected
Boolean value of expected state. Strings are interpreted as booleans. All strings are ${True} except the following: FALSE, NO, OFF, 0, UNCHECKED, NONE, ${EMPTY} (case-insensitive). Defaults to Unchecked.
message
overrides the default error message for assertion.
checked => True
unchecked => False
Keyword uses strict mode, see Finding elements for more details about strict mode.
Example:
Get Checkbox State [name=can_send_email] == checked
Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.
assertion_operator
See Assertions for further details. Defaults to None.
*assertion_expected
Expected values for the state
message
overrides the default error message for assertion.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Optionally asserts that the value matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
Available assertions:
== , != and contains / *= can work with multiple values
validate and evaluate only accept one single expected value
Other operators are not allowed.
Example:
Get Classes id=draggable == react-draggable box # Element has exactly these class names.Get Classes id=draggable validate "react-draggable-dragged" not in value # Element does not contain react-draggable-dragged class.
Gets elements or pages client size (clientHeight, clientWidth) as object {width: float, height: float}.
Arguments
Description
selector
Optional selector from which the client size shall be retrieved. If no selector is given the client size of the page itself is used (document.scrollingElement). See the Finding elements section for details about the selectors.
key
Optionally filters the returned values. If keys is set to ALL (default) it will return the client size as dictionary, otherwise it will just return the single value selected by the key.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the assertion
message
overrides the default error message for assertion.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Optionally asserts that the value matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
Returns a list of context ids based on the browser selection. See Browser, Context and Page for more information about Context and related concepts.
ALL and ANY are synonyms. ACTIVE and CURRENT are also synonyms.
Arguments
Description
context
The context to get the ids from. ALL will return all ids from selected browser(s), ACTIVE for the one active context of each selected browser.
browser
The browser id or selection to get the context ids from. ALL Context ids from all open browsers shall be fetched. ACTIVE Only context ids from the active browser shall be fetched. If a browser id is given and no browser with that id is open, the keyword fails.
The ACTIVE context of the ACTIVE Browser is the Current Context.
Returns information about the cookie named cookie as a Robot Framework dot dictionary or a string.
Arguments
Description
cookie
Name of the cookie to be retrieved.
return_type
Type of the return value. Can be either dictionary or string. Defaults to dictionary.
If return_type is dictionary or dict, then the keyword returns a Robot Framework dot dictionary. The dictionary contains all key value pairs of the cookie. If return_type is string or str, then the keyword returns the cookie as a string in format: name1=value1. The return value contains only the name and value keys of the cookie.
If no cookie is found with the given name, the keyword fails. The cookie dictionary contains details about the cookie. Keys available in the dictionary are documented in the table below.
Value
Explanation
name
The name of the cookie.
value
Value of the cookie.
domain
Specifies which hosts are allowed to receive the cookie.
path
Indicates a URL path that must exist in the requested URL, for example /.
expires
Lifetime of a cookie. Returned as a datetime object or None if no valid time is received.
httpOnly
When true, the cookie is not accessible via JavaScript.
secure
When true, the cookie is only used with HTTPS connections.
sameSite
Attribute that lets servers require that a cookie shouldn't be sent with cross-origin requests.
Returns cookies from the currently active browser context.
If return_type is dictionary or dict, then the keyword returns a list of Robot Framework dot dictionaries. Each dictionary contains all key value pairs of the cookie. See the Get Cookie keyword documentation for details about the dictionary keys and values.
If return_type is string or str, then the keyword returns the cookies as a string in format: name1=value1; name2=value2; name3=value3. The return value contains only name and value keys of the cookies. If no cookies are found, an empty list is returned.
Returns the credential matching the given id and/or rpId.
At least one of id_ and rpId must be given, otherwise the keyword fails. If both are given, the credential must match both of them. When more than one credential matches, the first match is returned. When no credential matches, the keyword fails.
Arguments
Description
id_
Base64url-encoded credential id.
rpId
Relying party id (typically the site's effective domain).
The returned credential is a dictionary with the following keys:
Key
Description
id
Base64url-encoded credential id.
rpId
Relying party id (typically the site's effective domain).
userHandle
Base64url-encoded user handle.
privateKey
Base64url-encoded PKCS#8 (DER) private key as a Secret.
publicKey
Base64url-encoded SPKI (DER) public key as a Secret.
The privateKey and publicKey are wrapped in the Secret type, so that their values are not shown in the Robot Framework log. The values themselves are available in the value attribute. Note that the node side of the library might write the whole credential, including the private key, as plain text to the playwright-log.txt file. See PlaywrightLogTypes for how to control that file.
See Install Credential for more information about how to use this keyword.
Example:
${credential} = Get Credential id_=${CREDENTIAL_ID}Should Be Equal ${credential["id"]} ${CREDENTIAL_ID}Should Be Equal ${credential["rpId"]} ${DOMAIN_NAME}Should Be Equal ${credential["userHandle"]} userhandleCreatedByTheAppShould Be Equal ${credential["privateKey"].value} privateKeyCreatedByTheAppShould Be Equal ${credential["publicKey"].value} publicKeyCreatedByTheApp
The keyword fails if there is no device with that name. The matching is case sensitive.
Allows a concise syntax to set website testing values to exact matches of specific mobile devices.
Use the returned descriptor by passing it to New Context. After creating a context with a device descriptor, make sure that your active page is in that context before using it. Usage:
Returns a selector string that points to the element found by selector.
The returned string is the selector Playwright resolved for the element. It is an ordinary selector, so it can be used as the first clause of another selector, chained with >>. Because it is a selector and not a captured DOM node, it is resolved again from the page on every use.
Arguments
Description
selector
Selector from which the element shall be retrieved. See the Finding elements section for details about the selectors.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Example:
${element} = Get Element \#username_field${option_value} = Get Property ${element} >> optionOne value # Locator is resolved from the page.${option_value} = Get Property ${element} >> optionTwo value # Locator is resolved again from the page.
Whether to find an exact match: case-sensitive and whole-string. Defaults to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace. This has no effect if RegExp is used or if TestID is used as strategy.
all_elements
If True, returns all matched elements as a list.
This keywords implements the following Playwright functions:
${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.
Returns the count of elements found with selector.
Arguments
Description
selector
Selector which shall be counted. See the Finding elements section for details about the selectors.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the assertion
message
overrides the default error message for assertion.
Optionally asserts that the count matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
Get the active states from the element found by selector.
This Keyword returns a list of states that are valid for the selected element.
Arguments
Description
selector
Selector of the corresponding object. See the Finding elements section for details about the selectors.
assertion_operator
See Assertions for further details. Defaults to None.
*assertion_expected
Expected states
message
overrides the default error message for assertion.
return_names
If set to False the keyword does return an IntFlag object (ElementState) instead of a list. ElementState may contain multiple states at the same time. Defaults to True.
Optionally asserts that the state matches the specified assertion. See Assertions for further details for the assertion arguments. By default, assertion is not done.
This keyword internally works with Python IntFlag. Flags can be processed using bitwise operators like & (bitwise AND) and | (bitwise OR). When using the assertion operators then, evaluate or validate the value contains the states as ElementState.
Example:
Get Element States h1 validate value & visible # Fails in case of an invisible elementGet Element States h1 then value & (visible | hidden) # Returns either ['visible'] or ['hidden']Get Element States h1 then bool(value & visible) # Returns ${True} if element is visible
The most typical use case would be to verify if an element contains a specific state or multiple states.
Example:
Get Element States id=checked_elem *= checkedGet Element States id=checked_elem not contains checkedGet Element States id=invisible_elem contains hidden attachedGet Element States id=disabled_elem contains visible disabled readonly
Elements do return the positive and negative values if applicable. As example, a checkbox does return either checked or unchecked while a text input element has none of those two states. Options of select elements have also either selected or deselected.
If an element is not attached to the DOM, so that it can not be found within 250ms, it is marked as detached as the only state.
stable state is not returned, because it would cause too high delay in that keyword.
Keyword uses strict mode, see Finding elements for more details about strict mode.
[{ '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'}]
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.
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.
Returns the property of the element found by selector.
Arguments
Description
selector
Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.
property
Requested property name.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the state
message
overrides the default error message for assertion.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Optionally asserts that the property value matches the expected value. See Assertions for further details for the assertion arguments. By default assertion is not done.
If assertion_operator is set and the property is not found, value is None and the keyword does not fail. If no assertion_operator is set and the property is not found, the keyword fails. See Get Attribute for examples.
Example:
Get Property h1 innerText == Login Page${property} = Get Property h1 innerText
Gets elements or pages current scroll position as object {top: float, left: float, bottom: float, right: float}.
It describes the rectangle which is visible of the scrollable content of that element. All values are measured from position {top: 0, left: 0}.
Arguments
Description
selector
Optional selector from which the scroll position shall be retrieved. If no selector is given the scroll position of the page itself is used (document.scrollingElement). See the Finding elements section for details about the selectors.
key
Optionally filters the returned values. If keys is set to ALL (default) it will return the scroll position as dictionary, otherwise it will just return the single value selected by the key.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the assertion
message
overrides the default error message for assertion.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Optionally asserts that the value matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
Gets elements or pages scrollable size as object {width: float, height: float}.
Arguments
Description
selector
Optional selector from which the scroll size shall be retrieved. If no selector is given the scroll size of the page itself is used. See the Finding elements section for details about the selectors.
key
Optionally filters the returned values. If keys is set to ALL (default) it will return the scroll size as dictionary, otherwise it will just return the single value selected by the key.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the assertion
message
overrides the default error message for assertion.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Optionally asserts that the state matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
Returns attributes of options of a select element as a list of dictionaries.
Each returned dictionary has the keys "index", "value", "label" and "selected".
Arguments
Description
selector
Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the state
message
overrides the default error message for assertion.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Optionally asserts that these match the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
Example:
Get Select Options //select[2] validate [v["label"] for v in value] == ["Email", "Mobile"]Get Select Options select#names validate any(v["label"] == "Mikko" for v in value)
Returns the specified attribute of selected options of the select element.
Arguments
Description
selector
Selector from which the info is to be retrieved. See the Finding elements section for details about the selectors.
option_attribute
Which attribute shall be returned/verified. Defaults to label.
assertion_operator
See Assertions for further details. Defaults to None.
*assertion_expected
Expected value for the state
message
overrides the default error message for assertion.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Optionally asserts that these match the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
== , != and contains / *= can work with multiple values
validate and evaluate only accept one single expected value
Other operators are not allowed.
Example:
Select Options By label //select[2] Email Mobile${selected_list} = Get Selected Options //select[2] # getterGet Selected Options //select[2] label == Mobile Mail #assertion contentSelect Options By label select#names 2 4Get Selected Options select#names index == 2 4 #assertion indexGet Selected Options select#names label *= Mikko #assertion containGet Selected Options select#names label validate len(value) == 3 #assertion length
Gets the computed style properties of the element selected by selector.
Arguments
Description
selector
Selector from which the style shall be retrieved. See the Finding elements section for details about the selectors.
key
Key of the requested CSS property. Retrieves "ALL" styles as dictionary by default. All css settings can be used as keys even if they are not all returned in the dictionary.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the assertion
message
overrides the default error message for assertion.
pseudo_element
Pseudo element to match. Defaults to None.
A pseudo element is a CSS functionality to add styles, for example ::before or ::after.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Optionally asserts that the style matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
When key is ALL, a dictionary is returned and only the sequence assertion operators ==, !=, contains / *=, validate and evaluate / then are allowed. Assertion formatters are not applied in that case.
Returns a selector string for the cell at the same column and row index as the selected elements.
The returned value is used like the one from Get Element.
Arguments
Description
table
selector must select the <table> element that contains both selected elements
column
selector can select any <th> or <td> element or one of their descendants.
row
selector can select any <tr> element or one of their descendants like <td> elements.
column and row can also consume index numbers instead of selectors. Indexes are starting from 0 and -1 is specific for the last element.
Selectors for column and row are directly appended to the table selector like this: f"{table} >> {column}" and f"{table} >> {row}".
GitHub
Slack
Real Name
mkorpela
@mkorpela
Mikko Korpela
aaltat
@aaltat
Tatu Aalto
xylix
@Kerkko Pelttari
Kerkko Pelttari
Snooz82
@René
René Rohner
Example:
${table}= Set Variable [id="Get Table Cell Element"] >> div.kw-docs table >> nth=1${e}= Get Table Cell Element ${table} "Real Name" "aaltat" # Returns element with text Tatu AaltoGet Text ${e} == Tatu Aalto${e}= Get Table Cell Element ${table} "Slack" "Mikko Korpela" # Returns element with text @mkorpelaGet Text ${e} == @mkorpela${e}= Get Table Cell Element ${table} "mkorpela" "Kerkko Pelttari" # column does not need to be in row 0Get Text ${e} == @mkorpela${e}= Get Table Cell Element ${table} 2 -1 # Index is also directly possibleGet Text ${e} == René Rohner
Returns the index (0 based) of a table cell within its row.
Arguments
Description
selector
can select any <th> or <td> element or one of their descendants. See the Finding elements section for details about the selectors.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the assertion
message
overrides the default error message for assertion.
Example:
${table}= Set Variable id=Get Table Cell Element >> div.kw-docs table #Table of keyword Get Table Cell Element${idx}= Get Table Cell Index ${table} >> "Real Name"Should Be Equal ${idx} ${2}Get Table Cell Index ${table} >> "@aaltat" == 1
Optionally asserts that the index matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
can select any <tr>, <th> or <td> element or one of their descendants. See the Finding elements section for details about the selectors.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the assertion
message
overrides the default error message for assertion.
Example:
${table}= Set Variable id=Get Table Cell Element >> div.kw-docs table #Table of keyword Get Table Cell Element${idx}= Get Table Row Index ${table} >> "@René"Should Be Equal ${idx} ${4}Get Table Row Index ${table} >> "@aaltat" == 2
Optionally asserts that the index matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
Returns text attribute of the element found by selector.
Keyword can also return the value property text of input or textarea elements. See the Finding elements section for details about the selectors.
Arguments
Description
selector
Selector from which the text is to be retrieved. See the Finding elements section for details about the selectors.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the state
message
overrides the default error message for assertion.
text_type
How text is returned. Possible values are allInnerTexts, allTextContents, innerText, inputValue, and innerHTML. Defaults to None, which returns the value of input and textarea elements and the inner text of all other elements.
Keyword uses strict mode, see Finding elements for more details about strict mode. The text_type argument determines how text is returned. The allInnerTexts and allTextContents will return a list of strings, while other types return a single string.
Optionally asserts that the text matches the specified assertion. See Assertions for further details for the assertion arguments. By default, assertion is not done.
Example:
${text} = Get Text id=important # Returns element text without assertion.${text} = Get Text id=important == Important text # Returns element text with assertion.${text} = Get Text //input == root # Returns input element text with assertion.${text} = Get Text id=important text_type=innerHTML # Returns element inner HTML.${text} = Get Text id=important text_type=allInnerTexts # Returns element inner text as list of strings.
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.
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.
Optionally filters the returned values. If keys is set to ALL (default) it will return the viewport size as dictionary, otherwise it will just return the single value selected by the key. Note: If a single value is retrieved, an assertion does not need a validate combined with a cast of value.
assertion_operator
See Assertions for further details. Defaults to None.
assertion_expected
Expected value for the assertion
message
overrides the default error message for assertion.
Optionally asserts that the state matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
If the page does not have a viewport size, for example because the context was created without one, None is returned and no assertion is done.
Example:
Get Viewport Size ALL == {'width':1280, 'height':720}Get Viewport Size width >= 1200
Time to wait for the page to load. If not defined, the library default timeout is used.
wait_until
When to consider the operation succeeded, defaults to load. The event can be either: domcontentloaded - consider the operation to be finished when the DOMContentLoaded event is fired. load - consider the operation to be finished when the load event is fired. networkidle - consider the operation to be finished when there are no network connections for at least 500 ms. commit - consider the operation to be finished when the network response is received and the document started loading.
Returns the HTTP status code of the navigation request as an integer, or 0 if no response was received.
Permissions to grant, given as separate arguments. See Permission for the available values, for example geolocation, notifications, camera or microphone.
origin
The origin to grant the permissions to, e.g. "https://example.com". If not given, the permissions are granted for all origins.
The dialog can be an alert, beforeunload, confirm or prompt dialog. This keyword must be called before the action, for example a click, which triggers the dialog.
The handler is registered on the current page and stays in effect for all following dialogs on that page. Calling this keyword again on the same page replaces the handler, so the latest call decides how dialogs are handled.
If a handler is not set, dialogs are dismissed by default.
The handler runs when the dialog appears, not while this keyword executes, so a failure to accept or dismiss the dialog can not be raised as a keyword failure. Such a failure is reported in the playwright-log.txt file only, which is linked into the Robot Framework log when a keyword fails.
Arguments
Description
action
How to handle the alert. Can be accept or dismiss.
prompt_input
The value to enter into the prompt. Only valid if the action argument equals accept. Defaults to an empty string.
Adds a highlight to elements matched by the selector. Provides a style adjustment.
Returns the number of highlighted elements. Keyword does not fail, if the selector matched zero elements in the page. Keyword does not scroll elements to viewport and highlighted element might be outside the viewport. Use Scroll To Element keyword to scroll element in viewport.
Arguments
Description
selector
Selectors which shall be highlighted. See the Finding elements section for details about the selectors.
duration
Sets for how long the selector shall be highlighted. Defaults to 5s => 5 seconds. If set to 0 seconds, the highlighting is not deleted.
width
Sets the width of the highlight border. Defaults to 2px.
style
Sets the style of the border. Defaults to dotted.
color
Sets the color of the border. Valid colors i.e. are: red, blue, yellow, pink, black
mode
Sets the mode of the highlight. Valid modes are: border (classic mode), playwright (Playwright's native one) and both. Defaults to border. If playwright is used, width, style and color are ignored and only one highlighting can happen at the same time.
Keyword does not fail if selector resolves to multiple elements.
Highlights which are created with duration=0 stay in the page until they are removed. Calling this keyword with an empty selector, for example Highlight Elements ${EMPTY}, removes all such highlights that were made with Playwright's native highlighting, in other words with mode=playwright or mode=both. Highlights drawn in border mode can not be removed that way.
Example:
Highlight Elements input#login_button duration=200ms${count} = Highlight Elements input#login_button duration=200ms width=4px style=solid color=\#FF00FFShould Be Equal ${count} ${5}
Moves the virtual mouse and scrolls to the element found by selector.
This method hovers over an element matching selector by performing the following steps:
Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
Wait for actionability checks on the matched element, unless the force option is set. If the element is detached during the checks, the whole action is retried.
Scroll the element into view if needed.
Use Mouse Move to hover over the center of the element, or the specified position.
Arguments
Description
selector
Selector element to hover. See the Finding elements section for details about the selectors.
position_x & position_y
A point to hover relative to the top-left corner of element bounding box. If not specified, hovers over some visible point of the element. Only positive values within the bounding-box are allowed. Both values must be given, otherwise the position is ignored.
Modifier keys to press. Ensures that only these modifiers are pressed during the hover, and then restores current modifiers back. If not specified, currently pressed modifiers are used. Valid modifier keys are Alt, Control, ControlOrMeta, Meta and Shift.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Performs an HTTP request in the current browser context
The request is sent with the browser's fetch from the currently active page, so a relative url is resolved against the URL of that page.
Arguments
Description
url
The request url, e.g. /api/foo.
method
The HTTP method for the request. Defaults to GET.
body
The request body. It is ignored for GET requests, because GET requests cannot have a body. If the body can be parsed as JSON, the Content-Type header for the request is automatically set to application/json, unless headers already contains that header. Defaults to None.
headers
A dictionary of additional request headers. Defaults to None.
The response is a Robot Framework dictionary with the following attributes:
status <int> The status code of the response.
statusText <str> Status text corresponding to status, e.g. OK or INTERNAL SERVER ERROR. This may not be available for all browsers.
body <dict> | <str> The response body. If the body can be parsed as a JSON object, it will be returned as Python dictionary, otherwise it is returned as a string.
headers <dict> A dictionary containing all response headers.
ok <bool> Whether the request was successful, i.e. the status is in the range 200-299.
url <str> The final URL of the response, after possible redirects.
redirected <bool> Whether the response is the result of a redirect.
type <str> The type of the response, e.g. basic or cors.
Here's an example of using Robot Framework dictionary variables and extended variable syntax to do assertions on the response object:
&{res}= HTTP /api/endpointShould Be Equal ${res.status} 200Should Be Equal ${res.body.some_field} some value
Installs the virtual WebAuthn authenticator into the context.
Takes no arguments.
Tags
CredentialSetter
Documentation
Installs the virtual WebAuthn authenticator into the context.
Overrides navigator.credentials.create() and navigator.credentials.get() in all current and future pages of the context. Call this before the page first touches navigator.credentials.
Until the authenticator is installed, no interception is in place and the page sees the platform's native (or absent) WebAuthn behavior. Create Credential installs the authenticator as well, so this keyword is mainly needed when the credentials are created by the application itself. There must be an open context, otherwise the keyword fails.
Example:
New ContextInstall CredentialNew Page ${SUT_URL}# Do something on the page that causes the page to call navigator.credentials.create()${credential_id} = Get Credential Id # This is a user keyword that returns the credential id from somewhere. Talk to your application team to find out how to get the credential id.${credential} = Get Credential id_=${credential_id} # This will return the credential that was created by the application and installed into the context.New ContextCreate Credential... rpId=${DOMAIN_NAME}... id_=${credential["id"]}... privateKey=${credential["privateKey"]}... publicKey=${credential["publicKey"]}... userHandle=${credential["userHandle"]}New Page ${SUT_URL}# User should be able to interact with the page using the installed credential.
insertText: Dispatches only input event, does not emit the keydown, keyup or keypress events. type: Sends a keydown, keypress/input, and keyup event for each character in the text.
input
The input string to be typed. No special keys possible.
delay
Time to wait between key presses in Robot Framework's time format. Defaults to 0 ms.
Attention: Argument type int for 'delay' in milliseconds has been changed to timedelta in Browser 14.0.0. Use Robot Framework time format with units instead.
Note: To press a special key, like Control or ArrowDown, use Keyboard Key. Modifier keys DO NOT affect these actions. For testing modifier effects use single key presses with Keyboard Key press
Press a keyboard key on the virtual keyboard or set a key up or down.
Arguments
Description
action
Determines whether the key should be released (up), held down (down) or pressed once (press). down and up are useful for combinations, i.e. with Shift.
key
The key to be pressed. Examples of valid keys are: F1 - F12, Digit0 - Digit9, KeyA - KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp , etc.
delay
Time the key is held down between keydown and keyup, in Robot Framework's time format. Only valid with action press, other actions raise an error. Defaults to 0 s. Example: 50 ms
Useful keys for down and up for example are: Shift, Control, Alt, Meta, ShiftLeft
Example execution:
Keyboard Key press SKeyboard Key press S delay=500 msKeyboard Key down ShiftKeyboard Key press ArrowLeftKeyboard Key press DeleteKeyboard Key up Shift
Note: Capital letters don't need to be written by the help of Shift. You can type them in directly.
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.
Optional list of reporters to create. Default is v8.
Returns the path to the output_folder.
The input_folder argument is the base folder where the coverage reports are located. The keyword will look into each subfolder and if the subfolder contains a "raw" folder, it will use the data from the "raw" folder for the combined report.
The output_folder argument is the folder where the combined report is saved. If the folder does not exist, it is created. If the folder exists, its content is deleted before the report is created.
The output_folder and input_folder must be full paths to the folders.
The name argument is optional and can be used to provide a name for the combined report. If it is not defined, the report is named "Browser library Merged Coverage Report".
The reports argument is optional and can be used to provide a list of reporters to create. Default is v8.
The keyword combines only the raw reports. To get raw reports, the Start Coverage keyword must be called with the raw=True argument. If no raw reports are found from the input_folder, the keyword fails. The keyword should be used when there is a need to combine multiple reports into a single report. For example, when tests are run in multiple pages. The example below demonstrates how to use the keyword.
Example:
New PageStart CoverageGo To ${LOGIN_URL}Test Feature X In The PageStop CoverageNew PageStart CoverageGo To ${LOGIN_URL}Test Feature Y In The PageStop CoverageMerge Coverage Reports ${OUTPUT_DIR}/browser/coverage ${OUTPUT_DIR}/browser/combined-coverage
Defines if it is a mouseclick (click), holding down a button (down) or releasing it (up).
x, y
Coordinates to move to before the action is executed. Both must be given, otherwise the action happens at the current mouse position.
button
One of left, middle or right. Defaults to left.
clickCount
Determines how often the button shall be clicked if action is equal to click. Defaults to 1.
delay
Delay in Robot Framework time format between the mousedown and mouseup event. Can only be set if the action is click. Defaults to 0 s.
Attention: Argument type int for 'delay' in milliseconds has been changed to timedelta in Browser 14.0.0. Use Robot Framework time format instead. For refactoring just add 'ms' after the delay number.
Delay Example:
Mouse Button click delay=100 msMouse Button click delay=${dyn_delay} ms
Moving the mouse between holding down and releasing it is possible with Mouse Move.
Example:
Hover "Obstacle" # Move mouse over the elementMouse Button down # Press mouse button downMouse Move Relative To "Obstacle" 500 # Drag mouseMouse Button up # Release mouse button
Moves the virtual mouse to the given coordinates, instead of to an element found by a selector.
The virtual mouse is left on the specified coordinates.
Arguments
Description
x & y
Absolute coordinates starting at the top left of the page.
steps
Number of intermediate steps for the mouse event. Often it is necessary to send more than one intermediate event to get the desired result. Defaults to 1.
Moves the mouse cursor relative to the selected element.
Arguments
Description
selector
Identifies the element whose center is the start-point.
x & y
Coordinates relative to the center of the element's bounding box.
steps
Number of intermediate steps for the mouse event. Often it is necessary to send more than one intermediate event to get the desired result. Defaults to 1.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Returns a stable identifier for the created browser.
Arguments
Description
browser
Opens the specified browser. Defaults to chromium.
headless
Set to False if you want a GUI. Defaults to True.
args
Additional arguments to pass to the browser instance. The list of Chromium flags can be found here. Defaults to None.
channel
Allows operating against the stock Google Chrome and Microsoft Edge browsers. Can only be used together with the chromium browser, otherwise the keyword fails. For more details see: Playwright documentation.
chromiumSandbox
Enable Chromium sandboxing. Defaults to False.
devtools
Chromium-only. Whether to auto-open a Developer Tools panel for each tab. Defaults to False.
downloadsPath
If specified, accepted downloads are downloaded into this folder. Otherwise, temporary folder is created and is deleted when browser is closed. Regarding file deletion, see the docs of Download and Promise To Wait For Download.
env
Specifies environment variables that will be visible to the browser. Dictionary keys are variable names, values are the content. Defaults to None.
executablePath
Path to a browser executable to run instead of the bundled one. If executablePath is a relative path, then it is resolved relative to current working directory. Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk. Defaults to None.
firefoxUserPrefs |Firefox user preferences. Learn more about the Firefox user preferences at about:config.
handleSIGHUP
Close the browser process on SIGHUP. Defaults to True.
handleSIGINT
Close the browser process on Ctrl-C. Defaults to True.
handleSIGTERM
Close the browser process on SIGTERM. Defaults to True.
ignoreDefaultArgs
If True, Playwright does not pass its own configuration args and only uses the ones from args. If a list is given, then the given default arguments are filtered out. Dangerous option; use with care. Defaults to None, which means Playwright's own default arguments are used.
proxy | Network Proxy settings. Structure: {'server': <str>, 'bypass': <Optional[str]>, 'username': <Optional[str]>, 'password': <Optional[str]>}. Robot Framework 7.4 Secret type is supported.|reuse_existing | If set to True, an existing browser instance that was created with the same arguments is reused. If no such browser exists, a new one is started. Defaults to True. |slowMo | Slows down Playwright operations by the given time, in Robot Framework time format. Useful so that you can see what is going on. Defaults to no delay. |timeout | Maximum time in Robot Framework time format to wait for the browser instance to start. Defaults to 30 seconds. Pass 0 to disable timeout. |
Returns a stable identifier for the created context that can be used in Switch Context.
Arguments
Description
acceptDownloads
Whether to automatically download all the attachments. Defaults to True where all the downloads are accepted.
baseURL
When using Go To, Wait For Request, Wait For Response or Wait For Navigation it takes the base URL in consideration by using the URL() constructor for building the corresponding URL. Unset by default. Examples: baseURL=http://localhost:3000 and navigating to /bar.html results in http://localhost:3000/bar.html. baseURL=http://localhost:3000/foo/ and navigating to ./bar.html results in http://localhost:3000/foo/bar.html. baseURL=http://localhost:3000/foo (without trailing slash) and navigating to ./bar.html results in http://localhost:3000/bar.html.
bypassCSP
Toggles bypassing page's Content-Security-Policy. Defaults to False.
clientCertificates
Specifies a client certificate for mTLS authentication, for example clientCertificates=[{'origin': 'https://playwright.dev', 'pfxPath': 'certificate.p12', 'passphrase': 'password'}]. NOTE: The origin needs to be exact without any path.
colorScheme
Emulates the prefers-color-scheme media feature, supported values are light, dark, no-preference and null. null disables the emulation.
defaultBrowserType
If no browser is open and New Context opens a new browser with defaults, this setting defines which browser is opened. Very useful together with the Get Device keyword.
deviceScaleFactor
Specify device scale factor (can be thought of as dpr). Defaults to 1.
extraHTTPHeaders
A dictionary containing additional HTTP headers to be sent with every request. All header values must be strings.
forcedColors
Emulates the forced-colors media feature, supported values are active, none and null. Defaults to none.
geolocation
A dictionary containing latitude and longitude and optionally accuracy to emulate. If latitude or longitude is not specified, the device geolocation won't be overridden.
hasTouch
Specifies if viewport supports touch events. Defaults to False.
Whether to ignore HTTPS errors during navigation. Defaults to False.
isMobile
Whether the meta viewport tag is taken into account and touch events are enabled. Defaults to False.
javaScriptEnabled
Whether or not to enable JavaScript in the context. Defaults to True.
locale
Specify user locale, for example en-GB, de-DE, etc.
offline
Toggles browser's offline mode. Defaults to False.
permissions
A list containing permissions to grant to all pages in this context. All permissions that are not listed here will be automatically denied.
proxy
Network proxy settings to use with this context. Defaults to None. NOTE: For Chromium on Windows the browser needs to be launched with the global proxy for this option to work. If all contexts override the proxy, global proxy will be never used and can be any string, for example proxy={ server: 'http://per-context' }.
recordHar
Enables HAR recording for all pages into a file. The path key must be a path to a file, for example recordHar={'path': '${OUTPUT_DIR}/har.file'}. If not specified, the HAR is not recorded. Make sure to close the context for the HAR to be saved.
recordVideo
Enables video recording for all pages into a folder. If not specified videos are not recorded. Make sure to close the context for videos to be saved. Video is not supported in remote browsers.
reducedMotion
Emulates the prefers-reduced-motion media feature, supported values are reduce and no-preference. Defaults to no-preference.
screen
Emulates consistent window screen size available inside web page via window.screen. Is only used when the viewport is set. Example {'width': 414, 'height': 896}
serviceWorkers
Whether to allow sites to register Service workers. Defaults to allow.
storageState
Restores the storage state created by the Save Storage State keyword. Must be a path to an existing file, otherwise the keyword fails. Relative paths are resolved against the current working directory.
timezoneId
Changes the timezone of the context. See ICU`s metaZones.txt for a list of supported timezone IDs.
tracing
Boolean True (recommendation) or file path or directory where the tracing file is saved. The string {contextid} will be replaced with the context id. Path to *.zip files can be absolute or relative to ${OUTPUT_DIR}. Path to folders can be absolute or relative to ${OUTPUT_DIR}/browser/traces. If boolean True or a directory is given, the trace file will automatically be named trace_{contextid}.zip. Temporary trace files will be saved to ${OUTPUT_DIR}/browser/traces/temp. Tracing is automatically closed when context is closed. Temporary trace files will be automatically deleted at start of each test execution. Trace file can be opened after the test execution by running command from shell: rfbrowser show-trace /path/to/trace.zip. Tracing can also be enabled by setting a Robot Framework variable or environment variable ROBOT_FRAMEWORK_BROWSER_TRACING to True.
userAgent
Specific user agent to use in this context.
viewport
A dictionary containing width and height. Emulates consistent viewport for each page. Defaults to 1280x720. None disables the default viewport. If width and height are 0, the viewport will scale with the window.
Example:
Test an iPhone ${device}= Get Device iPhone X New Context &{device} # unpacking here with & New Page http://example.com
A BrowserContext is the Playwright object that controls a single browser profile. Within a context caches and cookies are shared. See Playwright browser.newContext for a list of supported options.
If there's no open Browser this keyword will open one. Does not create pages. It is not possible to create a new context in a browser that was opened with New Persistent Context.
The httpCredentials and proxy arguments do support Robot Framework 7.4 Secret type. If Secret is used, the dictionary structure must be created before hand, example with Robot Framework's VAR syntax:
${user} ${password} = Get Secrets # Returns username and password as Robot Framework Secret typeVAR &{httpCredentials} = username=${user} password=${password}New Context httpCredentials=${httpCredentials}
Using dictionary literals with Robot Framework 7.4 Secret type is not supported, for example this will fail on variable conversion on Robot Framework side:
${user} ${password} = Get Secrets # Returns username and password as Robot Framework Secret typeNew Context httpCredentials={'username': ${secret}, 'password': ${secret}} # This will fail
A Page is the Playwright equivalent to a tab. See Browser, Context and Page for more information about Page concept.
Arguments
Description
url
Optional URL to navigate the page to. The url should include the protocol, for example https://.
wait_until
When to consider operation succeeded, defaults to load. Events can be either: domcontentloaded - consider operation to be finished when the DOMContentLoaded event is fired. load - consider operation to be finished when the load event is fired. networkidle - consider operation to be finished when there are no network connections for at least 500 ms. commit - consider operation to be finished when network response is received and the document started loading.
Returns NewPageDetails as dictionary for created page. NewPageDetails (dict) contains the keys page_id and video_path. page_id is a stable identifier for the created page. video_path is path to the created video or empty if video is not created.
This keyword returns a tuple of browser id, context id and page details. (New in Browser 15.0.0)
Argument
Description
userDataDir
Path to a User Data Directory, which stores browser session data like cookies and local storage. Note that Chromium's user data directory is the parent directory of the "Profile Path" seen at chrome://version. Pass an empty string to use a temporary directory instead.
browser
Browser type to use. Default is Chromium.
headless
Whether to run browser in headless mode. Defaults to True.
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}
Advances the clock by jumping forward in time and pauses it.
Arguments
Description
time
The time to pause the clock at.
Fires due timers at most once. This is equivalent to a user closing the laptop lid for a while and reopening it at the specified time and then pausing. Pause can not move the clock backwards.
Example:
Set Time 2024-10-31 17:34:00 # Set the clock to a specific timeDo Something # Implement this in your keywordPause At 2024-10-31 18:34:00 # Pause the clock at a specific timeCheck Something # Also this is implemented in your keywordResume Clock # Resume the clockDo Something Else # Do something after clock runs normally
Wrap a Browser library keyword and make it a promise.
The promised keyword is started in the background. Test execution continues without waiting for kw to finish.
Returns a reference to the promised keyword. Use Wait For or Wait For All Promises to wait for its result. Promises that are never waited for are waited for automatically at the end of the test, and a warning is logged.
Only Browser library keywords can be promised, any other keyword name fails the keyword.
Arguments
Description
kw
Keyword that will run asynchronously in the background.
*args
Keyword arguments as normally used.
Example:
${promise}= Promise To Wait For Response matcher= timeout=3Click \#delayed_request${body}= Wait For ${promise}
Returns a promise that waits for the next download event on the page.
To enable downloads the context's acceptDownloads needs to be true.
With the default file path downloaded files are deleted when the context the download happened in is closed.
If browser is connected remotely with Connect To Browser then saveAs must be set to store it locally where the browser runs!
Arguments
Description
saveAs
Defines path where the file is saved persistently. File will also temporarily be saved in playwright context's default download location. If empty, generated unique path (GUID) is used and file is deleted when the context is closed.
wait_for_finished
If true, promise will wait for download to finish. If false, promise will resolve immediately after download has started.
download_timeout
Maximum time to wait for the download to finish, if wait_for_finished is set to True. If the download is not finished within this time, it is cancelled and the keyword fails. If not set, the keyword waits until the download is finished.
Keyword returns dictionary of type DownloadInfo which contains downloaded file path and suggested filename as well as state and downloadID. Example:
If wait_for_finished is False, saveAs is an empty string, state is in_progress and downloadID contains an id which can be used with Get Download State to check the download later.
The keyword New Browser has a downloadsPath setting which can be used to set the default download directory. If saveAs is set to a relative path, the file will be saved relative to the browser's downloadsPath setting or if that is not set, relative to the Playwright's working directory. If saveAs is set to an absolute path, the file will be saved to that absolute path independent of downloadsPath.
If the URL for the file to download shall be used, Download keyword may be a simpler alternative way to download the file.
The waited promise returns a dictionary which contains saveAs and suggestedFilename as keys. The saveAs contains the location where the file is downloaded and suggestedFilename contains the suggested name for the download. The suggestedFilename is typically computed by the browser from the Content-Disposition response header or the download attribute. See the spec on whatwg. Different browsers can use different logic for computing it.
Example usage:
New Context acceptDownloads=TrueNew Page ${LOGIN_URL}${dl_promise} Promise To Wait For Download /path/to/download/file.nameClick id=file_download${file_obj}= Wait For ${dl_promise}File Should Exist ${file_obj}[saveAs]Should Be True ${file_obj.suggestedFilename}
Sets the keyword to execute, when a Browser keyword fails.
Arguments
Description
keyword
The name of a keyword that will be executed if a Browser keyword fails. It is possible to use any available keyword, including user keywords or keywords from other libraries.
*args
The arguments to the keyword if any.
scope
Scope defines the lifetime of this setting. Available values are Global, Suite or Test / Task. See Scope Setting for more details.
The initial keyword to use is set when importing the library, and the keyword that is used by default is Take Screenshot fail-screenshot-{index}. Taking a screenshot when something failed is a very useful feature, but notice that it can slow down the execution.
It is possible to use string NONE or any other robot falsy name, case-insensitively, as well as Python None to disable this feature altogether.
This keyword returns an object which contains the previously registered failure keyword. The return value can always be used to restore the original value later. The returned object contains the keyword name and the possible arguments used for the keyword.
If the Take Screenshot keyword is registered as run on failure keyword without positional arguments and without the filename argument, then the default value of the filename argument is not used as screenshot file name. Instead, ${TEST NAME}_FAILURE_SCREENSHOT_{index} in the output directory is used as file name. If there is a need to use the default value of the filename argument, use robotframework-browser-screenshot-{index} as the filename argument value.
Example:
Register Keyword To Run On Failure Take Screenshot # Uses ${TEST NAME}_FAILURE_SCREENSHOT_{index} as filenameRegister Keyword To Run On Failure Take Screenshot robotframework-browser-screenshot-{index} # Uses robotframework-browser-screenshot-{index} as filename${previous kw}= Register Keyword To Run On Failure NONE # Disables run on failure functionality.Register Keyword To Run On Failure ${previous kw}Register Keyword To Run On Failure Take Screenshot fullPage=TrueRegister Keyword To Run On Failure Take Screenshot failure-{index} fullPage=True
Maximum time for the reload to succeed. If not given, the currently set browser timeout is used.
waitUntil
When to consider the operation succeeded, defaults to load.
waitUntil events can be either: domcontentloaded - consider the operation to be finished when the DOMContentLoaded event is fired. load - consider the operation to be finished when the load event is fired. networkidle - consider the operation to be finished when there are no network connections for at least 500 ms. commit - consider the operation to be finished when the network response is received and the document started loading.
The locator must be exactly the same string that was used as the selector argument when the handler was added. Handlers are tied to the page in which they were added, therefore this keyword removes the handler from the active page only. If no handler is found, the keyword does not fail, it only logs that no handler was found.
Saving a PDF is currently only supported in Chromium and only when the browser is running in headless mode.
Arguments
Description
path
Where the PDF is saved. If the path is not absolute, the file is saved relative to ${OUTPUT_DIR}.
displayHeaderFooter
Display header and footer. Defaults to false.
footerTemplate
HTML template for the print footer. Should use the same format as the headerTemplate.
format
Paper format. If set, takes priority over the width and height arguments. Defaults to Letter.
headerTemplate
HTML template for the print header. Both templates are only rendered when displayHeaderFooter is true. See the detailed explanation below.
height
Paper height, accepts values labeled with units.
landscape
Paper orientation. Defaults to false.
margin
Defines the PDF margins, see PdfMarging for more details. Defaults to 0px on all sides.
outline
Whether or not to embed the document outline into the PDF. Defaults to false.
pageRanges
Paper ranges to print, e.g. 1-5, 8, 11-13. Defaults to the empty string, which means print all pages.
preferCSSPageSize
Give any CSS @page size declared in the page priority over what is declared in the width and height or format arguments. Defaults to false, which will scale the content to fit the paper size.
printBackground
Print background graphics. Defaults to false.
scale
Scale of the webpage rendering. Defaults to 1. Scale amount must be between 0.1 and 2.
tagged
Whether or not to generate a tagged (accessible) PDF. Defaults to false.
width
Paper width, accepts values labeled with units.
headerTemplate and footerTemplate should be valid HTML markup. The following classes can be used to inject printing values into them:
date formatted print date
title document title
url document location
pageNumber current page number
totalPages total pages in the document
All possible units are:
px - pixel
in - inch
cm - centimeter
mm - millimeter
headerTemplate and footerTemplate markup have the following limitations:
Script tags inside the templates are not evaluated.
New Browser Chromium headless=TrueNew Page ${URL}Emulate Media media=screen${pdf_path} = Save Page As Pdf page.pdfShould Be Equal ${pdf_path} ${OUTPUT_DIR}${/}page.pdf
Saves the current active context storage state to a file.
Web apps use cookie-based or token-based authentication, where authenticated state is stored as cookies or in local storage. This keyword retrieves the storage state from authenticated contexts and saves it to disk. Then New Context can be created with prepopulated state.
Please note that the state file may contain secrets and should not be shared with people outside of your organisation.
Arguments
Description
path
Where the state file is written. Relative paths are resolved against the current working directory and missing parent directories are created. If the file already exists, it is overwritten. If not given, a file with a generated name is created in ${OUTPUTDIR}/browser/state. The absolute path of the written file is returned.
indexedDB
Also save IndexedDB. Needed by applications, like Firebase, which store authentication tokens in IndexedDB.
credentials
Also save the context's virtual WebAuthn credentials, as created by Create Credential. This is not related to the httpCredentials argument of New Context, which is about HTTP authentication.
Files in ${OUTPUTDIR}/browser/state are automatically deleted when new test execution starts. To keep a state file over several executions, save it with path to a location outside of that folder. File path is returned by the keyword.
Example:
Test Case New context New Page https://login.page.html # Perform login VAR ${username: Secret} %{USERNAME} # Convert environment variable to secret VAR ${password: Secret} %{PASSWORD} # Convert environment variable to secret Fill Secret id=username ${username} Fill Secret id=password ${password} Click id=button Get Text id=header == Something # Save storage to disk ${state_file} = Save Storage State # Create new context with saved state New context storageState=${state_file} New Page https://login.page.html # Login is not needed because authentication is read from state file Get Text id=header == Something
Scrolls an element or the page relative from current position by the given values.
Arguments
Description
selector
Selector of the element. If the selector is ${None} or ${Empty} the page itself is scrolled. To ensure an element is in view use Hover instead. See the Finding elements section for details about the selectors.
vertical
Defines how far and in which direction to scroll vertically. It can be a positive or negative number. Positive scrolls down, like 50, negative scrolls up, like -50. It can be a percentage value of the absolute scrollable size, like 9.95% or negative like -10%. It can be the string height to scroll exactly one visible height down, or -height to scroll one visible height up. Be aware that some pages do lazy loading and load more content once you scroll down. The percentage of the current scrollable height is used and may change. Defaults to height.
horizontal
Defines how far and in which direction to scroll horizontally. Works the same way as vertical, but positive values scroll to the right and negative values to the left. width scrolls exactly one visible range to the right. Defaults to 0.
behavior
Defines whether the scroll happens instantly or smoothly. Defaults to auto.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Scrolls an element or the page to an absolute position based on given coordinates.
Arguments
Description
selector
Selector of the element. If the selector is ${None} or ${Empty} the page itself is scrolled. To ensure an element is in view use Hover instead. See the Finding elements section for details about the selectors.
vertical
Defines where to scroll vertically. It can be a positive number, like 300. It can be a percentage value of the absolute scrollable size, like 50%. It can be a string defining the top or the bottom of the scroll area. < top
bottom > Be aware that some pages do lazy loading and load more content once you scroll down. Bottom defines the currently known bottom coordinate. Defaults to top.
horizontal
Defines where to scroll horizontally. Works the same way as vertical, but defines < left
right > as start and end. Defaults to left.
behavior
Defines whether the scroll happens instantly or smoothly. Defaults to auto.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Selects options from select element found by selector.
Arguments
Description
selector
Selector of the <select> tag. See the Finding elements section for details about the selectors.
attribute
Attribute to select options by. Can be value, label, text or index. Where label and text are same.
*values
Values to select.
Returns a list of the options which the keyword was able to select. The type of the list items matches the attribute definition. For example, if attribute equals label, the returned list contains label values. Or in case of index, it contains the selected indexes.
Keyword uses strict mode, see Finding elements for more details about strict mode.
If no values to select are passed, all options of the element are deselected. The keyword fails if none of the given values matches an option.
Example:
${selected} = Select Options By select[name=preferred_channel] label Direct mailList Should Contain Value ${selected} Direct mail${selected} = Select Options By select[name=interests] value males females othersList Should Contain Value ${selected} malesList Should Contain Value ${selected} femalesList Should Contain Value ${selected} othersLength Should Be ${selected} 3${selected} = Select Options By select[name=possible_channels] index 0 2List Should Contain Value ${selected} 0List Should Contain Value ${selected} 2${selected} = Select Options By select[name=interests] text Males FemalesList Should Contain Value ${selected} MalesList Should Contain Value ${selected} Females
Dictionary of keywords and formatters, where the key is the name of the keyword where the formatters are applied. The dictionary value is a list of formatters which are applied. Formatters for a defined keyword are always overwritten. An empty list will clear all formatters for the keyword. If formatters is an empty dictionary, then all formatters are cleared from all keywords, in the Global scope, regardless of the scope argument.
scope
Defines the lifetime of the formatter, possible values are Global, Suite and Test.
Returns the formatters which were in use before this keyword was called. Formatters defined as lambda functions are not included in the returned value.
It is possible to define own formatters as lambda functions.
Example:
Set Assertion Formatters {"Get Text": ["strip", "normalize spaces"]} # This will convert all kinds of spaces to a single space and remove spaces from the start and end of the string.Set Assertion Formatters {"Get Title": ["apply to expected","lambda x: x.replace(' ', '')"]} # This will remove all spaces from the string.${value} = Get Text //div == ${SPACE}Expected${SPACE * 2}TextShould Be Equal ${value} Expected Text
Set default runBeforeUnload value when Close Page is called indirectly.
Close Page is called indirectly when automatic page closing is done. The default value is false and this keyword can be used to change value. Returns the old runBeforeUnload value.
Latitude can be between -90 and 90 and longitude can be between -180 and 180. The accuracy of the location must be a non-negative number and defaults to 0. When creating the context, grant the geolocation permission so that pages can read the geolocation.
Arguments
Description
latitude
Latitude between -90 and 90.
longitude
Longitude between -180 and 180.
accuracy
Non-negative accuracy value. Defaults to 0.
Example:
${permissions} = Create List geolocationNew Context permissions=${permissions}Set Geolocation 60.173708 24.982263 3 # Points to Korkeasaari in Helsinki.
Sets presenter mode for element highlighting during test execution.
Arguments
Name
Default
Type
moderequired
Union
Returns
Union
Tags
BrowserControlSetter
Documentation
Sets presenter mode for element highlighting during test execution.
Presenter mode highlights elements found by keywords, which is useful for test debugging and demonstration. When enabled, the element is scrolled into view and highlighted with a border for a while to visually show what the keyword found.
Arguments
Description
mode
When set to True, enables presenter mode with default settings. When set to False, disables presenter mode. Can also be a dictionary containing the highlighting configuration options as defined in HighLightElement. Fields which are not given use their default values: duration 2 seconds, width 2px, style dotted and color blue.
The keyword returns the previous presenter mode value, allowing you to restore it later.
Example:
${old_mode} = Set Presenter Mode TrueClick //button # Element will be highlightedSet Presenter Mode ${old_mode} # Restore previous mode# With custom highlighting configurationVAR &{config}... duration=5 seconds... width=3px... style=dotted... color=redSet Presenter Mode ${config}Get Text //input # Will use custom highlight settingsSet Presenter Mode False # Turn off highlighting
Sets the timeout used in retrying assertions when they fail.
Arguments
Description
timeout
Assertion retry timeout will determine how long Browser library will retry an assertion to be true.
scope
Scope defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope for more details.
The other keyword Set Browser Timeout controls how long Playwright will wait on the node side for elements to fulfill the requirements of the specific keyword.
Returns the previous value of the assertion retry timeout.
Example:
Set Browser Timeout 10 seconds${old} = Set Retry Assertions For 30sGet Title == Login PageSet Retry Assertions For ${old}
The example waits 10 seconds in Playwright to get the page title and the library will retry for 30 seconds to make sure that the title is correct.
Sets the prefix for all selectors in the given scope.
Arguments
Description
prefix
Prefix for all selectors. Prefix and selector will be separated by a single space. Use ${None} or ${EMPTY} to disable the prefix.
scope
Scope defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope for more details.
Returns the previous value of the prefix.
Example:
${old} = Set Selector Prefix iframe#embedded_page >>>Click button#login_btn # Clicks on button inside iframe with the selector iframe#embedded_page >>> button#login_btnSet Selector Prefix ${old}
Example will click on button with id login_btn inside iframe with id embedded_page. The resulting selector will be iframe#embedded_page >>> button#login_btn.
The effect of this prefix can be disabled by prefixing any selector with !prefix , with a trailing space, for single keyword calls, i.e. !prefix id=btn_outside_a_frame
Restores a storage state file into the current active context.
Clears the cookies, local storage, IndexedDB and virtual WebAuthn credentials of the currently active context and replaces them with the ones from the path file, which must have been created by Save Storage State. Unlike creating a New Context with the storageState argument, the context and all of its pages stay open.
Pages that are already open keep the state they have loaded into memory. Reload them, with the Reload keyword, to make them see the restored state. Cookies and local storage are readable right away, without a reload, but the application has read them long ago.
Note that sessionStorage is not part of a storage state, neither when saving nor when restoring. It survives this keyword unchanged, so an application which keeps data of the previous user there still has it after the state was replaced.
Restoring a state which was saved with credentials=True installs the virtual WebAuthn authenticator into the context, the same way Install Credential does. Real authenticators do not work in that context afterwards.
Arguments
Description
path
Path to a state file created by Save Storage State. Relative paths are resolved against the current working directory. The keyword fails if the file does not exist.
timeout
Time to wait for the state to be restored. If not defined, the library default timeout is used. Pass 0 to disable the timeout.
reload_pages
Which pages are reloaded while the state is restored, see ReloadPages. Only relevant when the state file contains IndexedDB.
Restoring IndexedDB
Restoring IndexedDB deletes the databases of the origin first, and that does not finish while any client of that origin holds an open connection to them. An application which keeps its connection open, which is the normal pattern when authentication tokens are stored in IndexedDB, therefore blocks the restore indefinitely. Playwright does not time out on its own, see playwright#42258.
This keyword works around that by navigating the pages of the affected origins to about:blank, restoring the state, and navigating them back to the url they had before. Use reload_pages to control which pages that applies to. A reload is needed in any case, because deleting the databases closes the connection of the application as well.
A service worker of the origin can hold a connection open too, and no value of reload_pages helps against that, because a service worker outlives the pages. The keyword then fails when timeout expires.
reload_pages=none detects a blocking connection up front and fails immediately instead of waiting for the timeout. That detection needs indexedDB.databases(), which older browsers, Firefox before 126 among them, do not have. There the keyword cannot tell whether a connection blocks and falls back to waiting for timeout.
Example:
New ContextNew Page https://login.page.html # Perform login as first user${user_a} = Save Storage State indexedDB=True # Perform login as second user${user_b} = Save Storage State indexedDB=True # Switch back to the first user without creating a new contextSet Storage State ${user_a}ReloadGet Text id=current-user == userA
When set to True, keywords that search elements will use Playwright strict mode and fail if the selector matches more than one element. When set to False, such keywords do not fail but operate on the first matching element.
scope
Scope defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope for more details.
The keyword returns the strict mode value which was in use before this keyword was called.
Strict mode is enabled by default. The initial value can also be set with the strict argument in the library importing. Strict mode is applied only to those keywords which state in their documentation that they use strict mode, see Finding elements for more details.
Example:
${old_mode} = Set Strict Mode FalseGet Text //input # Does not fail even if the selector matches multiple elementsSet Strict Mode ${old_mode}
The time to set. Supports Robot Framework date and time format
clock_type
The clock type to set. Default is install.
fixed makes Date.now and new Date() always return the same fake time, while all timers keep running.
system sets the current system time but does not trigger any timers.
install installs fake timers, which are used to manually control the flow of time in tests. They allow you to advance time, fire timers, and control the behavior of time-dependent functions.
Sets the current page's viewport size to the specified dimensions.
In the case of multiple pages in a single browser, each page can have its own viewport size. However, New Context allows setting the viewport size (and more) for all later opened pages in the context at once.
Set Viewport Size will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size with New Context before opening the page itself.
Controls if the keyword banner is shown on page or not.
The keyword call banner is a CSS overlay that shows the currently executed keyword directly on the page. This is useful for debugging and for showing the test execution on video recordings. By default, the banner is not shown on the page except when running in presenter mode.
The banner can also be controlled by an import setting of the Browser library. (see Importing section)
Arguments
Description
show
If True, the banner is shown on the page. If False, the banner is not shown on the page. If ${None}, the banner is shown on the page only when running in presenter mode.
style
Additional CSS styles to be applied to the banner. These styles may override the existing ones for the banner.
scope
Scope defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope for more details.
Returns the previous settings as a dictionary with the keys show and style.
Example:
Show Keyword Banner True top: 5px; bottom: auto; left: 5px; background-color: #00909077; font-size: 9px; color: black; # Show banner on top left corner with custom stylesShow Keyword Banner False # Hide banner
Coverage must be started when the page is open and before any action is performed on the page. Coverage will be stored when calling the Stop Coverage keyword or when the page or context is closed. This is done automatically when using the auto closing.
The raw argument saves the raw coverage data in the coverage folder. The raw data is needed to combine multiple coverage reports into a single report. A single report can be created with the rfbrowser coverage /path/to/basefolder/ /path/to/outputfolder/ command. Please note that the raw argument is ignored if the config_file is defined. In that case the user is responsible for also setting the raw reporter in the config file. To see more details about combining coverage data, run the rfbrowser coverage --help command.
Example:
New PageStart CoverageGo To ${LOGIN_URL}Do Something In The PageStop Coverage
Creates a coverage report by using monocart-coverage-reports To see the default and all possible options, see options.js file for more details.
If coverage was not started, the keyword returns None. Otherwise it returns the path to the generated HTML report file, or the path to the coverage folder if no HTML file is found from the folder. The latter can happen when the report format or output folder has been changed with the config_file argument of the Start Coverage keyword.
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.
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.
Switches the active browser page to another open page by id or NEW.
Returns a stable identifier id for the previous page. See Browser, Context and Page for more information about Page and related concepts.
Arguments
Description
id
The id or alias of the page to switch to. Example: page=8baf2991-5eaf-444d-a318-8045f914e96a or NEW. Can be a string or a dictionary returned by New Page Keyword. A page id can be fetched from the browser catalog when returned by Get Browser Catalog. NEW can be used to switch to a pop-up that just has been opened by the webpage, CURRENT can be used to switch to the active page of a different context or browser, identified by their id.
context
The context in which to search for that page. CURRENT for the currently active context, ALL to search in all open contexts or the id of the context where to switch page.
browser
The browser in which to search for that page. CURRENT for the currently active browser, ALL to search in all open browsers or the id of the browser where to switch page.
If a page id is given, the context and browser arguments are ignored and the page is searched from all open browsers.
NEW may time out if no new page is opened before the library timeout expires.
Example:
Click button#pops_up # Open new page${previous} = Switch Page NEW
Takes a screenshot of the current window or element and saves it to disk.
Arguments
Description
filename
Filename into which to save. The file will be saved into the Robot Framework ${OUTPUTDIR}/browser/screenshot directory by default, but it can be overwritten by providing a custom path or filename. String {index} in the filename will be replaced with a rolling number. Use this to not overwrite filenames. If filename equals to UUID (case insensitive), then the filename is created by Python uuid; https://docs.python.org/3/library/uuid.html. If filename equals to EMBED (case insensitive) or ${NONE}, then the screenshot is embedded as a Base64 image into the log.html. The image is saved temporarily to the disk and a warning is displayed if removing the temporary file fails. The ${OUTPUTDIR}/browser/screenshot directory is removed at the first suite startup.
selector
Take a screenshot of the element matched by selector. See the Finding elements section for details about the selectors. If not provided, take a screenshot of the current viewport.
crop
Crops the taken screenshot to the given box. It takes the same dictionary as returned from Get BoundingBox. Cropping only works on a page screenshot, so when no selector is given.
disableAnimations
When set to True, stops CSS animations, CSS transitions and Web Animations. Animations get different treatment depending on their duration: - finite animations are fast-forwarded to completion, so they'll fire the transitionend event. - infinite animations are cancelled to initial state, and then played over after the screenshot.
fileType
png or jpeg. Specifies the screenshot type, defaults to png.
fullPage
When True, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to False.
highlight_selector
Highlights elements while taking the screenshot. Highlight method is playwright. This highlighting also automatically happens if the Robot Framework variable ${ROBOT_FRAMEWORK_BROWSER_FAILING_SELECTOR} is set to a selector string and is available on page. This is the case if highlight_on_failure has been set to True when importing Browser library.
log_screenshot
When set to False the screenshot is taken but not logged into log.html.
mask
Specify selectors that should be masked when the screenshot is taken. Masked elements will be overlaid with a pink box #FF00FF that completely covers their bounding box. The argument can take a single selector string or a list of selector strings if multiple different elements should be masked.
maskColor
Specify the color of the overlay box for masked elements, in CSS color format. Default color is pink #FF00FF.
omitBackground
Hides the default white background and allows capturing screenshots with transparency. Not applicable to jpeg images.
quality
The quality of the image, between 0-100. Not applicable to png images.
scale
css or device. css will reduce the image size and device keeps the image in its original size. Defaults to device.
return_as
Defines what this keyword returns. Possible values are documented in ScreenshotReturnType. It can be either a path to the screenshot file as string or Path object, or the image data as bytes or base64 encoded string. When the screenshot is embedded into the log, path_string returns the string EMBED.
timeout
Maximum time how long taking the screenshot can last, defaults to the library timeout. Supports Robot Framework time format, like 10s or 1 min, pass 0 to disable the timeout. The default value can be changed by using the Set Browser Timeout keyword.
Keyword uses strict mode if selector is defined. See Finding elements for more details about strict mode.
Example
Take Screenshot # Takes screenshot from page with default filenameTake Screenshot selector=id=username_field # Captures element in image# Takes screenshot with jpeg extension, defines image quality and timeout how long taking screenshot should lastTake Screenshot fullPage=True fileType=jpeg quality=50 timeout=10sTake Screenshot EMBED # Screenshot is embedded as Base64 image to the log.html.Take Screenshot UUID # Takes screenshot from page with filename generated by: https://docs.python.org/3/library/uuid.html.
Requires that the hasTouch option of New Context is set to true. This method taps the element by performing the following steps:
Wait for actionability checks on the element, unless the force option is set.
Scroll the element into view if needed.
Use page.touchscreen to tap the center of the element, or the specified position.
Wait for initiated navigations to either succeed or fail.
Arguments
Description
selector
Selector element to tap. See the Finding elements section for details about the selectors.
*modifiers
Modifier keys to press. Ensures that only these modifiers are pressed during the tap, and then restores current modifiers back. If not specified, currently pressed modifiers are used. Modifiers can be specified in any order, and multiple modifiers can be specified. Valid modifier keys are Alt, Control, ControlOrMeta, Meta and Shift.
force
Whether to bypass the actionability checks. Defaults to False.
noWaitAfter
Deprecated. This option has no effect. Defaults to False.
position_xposition_y
A point to tap relative to the top-left corner of element bounding-box. Only positive values within the bounding-box are allowed. Both values must be given, otherwise the position is ignored. If not specified, taps some visible point of the element.
trial
When set, this method only performs the actionability checks and skips the action. Defaults to False.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Example:
New Context hasTouch=${True}New Page ${URL}Tap css=input#login_button
Types the given secret into the text field found by selector.
Arguments
Description
selector
Selector of the text field. See the Finding elements section for details about the selectors.
secret
Supports Robot Framework 7.4 Secret type as normal variable (with curly braces). Also environment variable name with % prefix or a local variable with $ prefix that has the secret text value (without curly braces).
delay
Delay between the single key strokes. It may be either a number or a Robot Framework time string. Time strings are fully explained in an appendix of Robot Framework User Guide. Defaults to 0 ms. Example: 50 ms
clear
Set to False if the field should not be cleared before typing. Defaults to True.
This keyword does not log the secret in Robot Framework logs, but if Playwright debug logs are enabled, the secret will be visible as plain text in the Playwright debug logs, regardless of the Robot Framework log level or how secret is resolved.
This keyword supports Robot Framework 7.4 Secret variable type, which is the recommended way if you are using Robot Framework 7.4 or newer.
For older Robot Framework versions the keyword supports resolving secrets from environment variables and Robot Framework variables in the following ways. The keyword resolves the secret from a Robot Framework variable internally, when the secret variable is prefixed with $, without the curly braces. Example: $Password will resolve to the ${Password} Robot Framework variable.
If the secret variable is prefixed with %, the library will resolve the corresponding environment variable. Example: %ENV_PWD will resolve to the %{ENV_PWD} environment variable.
Using normal Robot Framework variables like ${password}, which are not Secret type variables, will not work!
Normal plain text will not work. If you want to use plain text, use the Type Text keyword instead.
This keyword also works with a cryptographic cipher text that has been encrypted by CryptoLibrary. See CryptoLibrary for more details.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Types the given txt into the text field found by selector.
Sends a keydown, keypress/input, and keyup event for each character in the text.
Arguments
Description
selector
Selector of the text field. See the Finding elements section for details about the selectors.
txt
Text for the text field.
delay
Delay between the single key strokes. It may be either a number or a Robot Framework time string. Time strings are fully explained in an appendix of Robot Framework User Guide. Defaults to 0 ms. Example: 50 ms
clear
Set to False if the field should not be cleared before typing. Defaults to True.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Uploads file from path to file input element matched by selector.
Fails if the upload is not done before the library timeout. Therefore it may be necessary to increase the timeout with Set Browser Timeout. It is possible to upload multiple files or folders by defining additional files or folders in extra_paths.
If a path is a directory, all files from the directory are uploaded. Subdirectories are not included. It is possible to upload files and directories with the same keyword. The keyword fails if a given path does not exist.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Arguments
Description
selector
Identifies the file input element.
path
Path to the file or folder to be uploaded. Can also be a FileUploadBuffer dictionary.
extra_paths
Additional paths to files or folders to be uploaded.
If path is a FileUploadBuffer dictionary, then the structure should be:
{ 'name': str, 'mimeType': str, 'buffer': str}
If path argument is FileUploadBuffer, then extra_paths argument is not supported and using it will raise an error.
Upload single file example:
Upload File By Selector //input[@type='file'] big_file.zip
Upload many files example:
Upload File By Selector //input[@type='file'] file1.zip file2.zip file3.zip
Upload folder example:
Upload File By Selector //input[@type='file'] /path/to/folder
Upload as buffer example:
${text} = Get File /path/to/file # Read file from diskVAR &{buffer} name=not_here.txt mimeType=text/plain buffer=${text} # Create buffer dictionaryUpload File By Selector id=file_chooser ${buffer} # Upload buffer
Waits for promises to finish and returns results from them.
Arguments
Name
Default
Type
*promises
Future
Tags
Wait
Documentation
Waits for promises to finish and returns results from them.
Returns a single result if only one promise is waited for. Otherwise it returns a list of results in the same order as the promises were given. If one of the promises fails, then this keyword will fail.
See Promise To for more information about promises.
Returns a promise to wait for next dialog on page, handles it with action and optionally verifies the dialogs text.
Dialog/alert can be any of alert, beforeunload, confirm or prompt.
Arguments
Description
action
How to handle the alert. Can be accept or dismiss.
prompt_input
The value to enter into the prompt. Only valid if the action argument equals accept. Defaults to an empty string.
text
Optional text to verify the dialog text with.
timeout
Optional timeout in Robot Framework time format. Defaults to the library timeout.
The main difference between this keyword and Handle Future Dialogs is that the Handle Future Dialogs keyword is automatically set as a promise, but this keyword must be called as an argument to the Promise To keyword. Also this keyword can optionally verify the dialog text and returns it. If the text argument is None or is not set, the dialog text is not verified.
Example with returning text:
${promise} = Promise To Wait For Alert action=acceptClick id=alerts${text} = Wait For ${promise}Should Be Equal ${text} Am an alert
Example with text verification:
${promise} = Promise To Wait For Alert action=accept text=Am an alertClick id=alerts${text} = Wait For ${promise}
Returns a promise to wait for multiple dialogs on a page.
Handles each alert/dialog with actions and optionally verifies the dialog texts. Dialog/alert can be any of alert, beforeunload, confirm or prompt.
Arguments
Description
actions
List of how to handle the alerts. Can be accept or dismiss.
prompt_inputs
List of the values to enter into the prompts. Only valid if the corresponding action equals accept. Use None if no input is needed.
texts
List of optional texts to verify the dialog texts with. Use None if text verification should be disabled.
timeout
Optional timeout in Robot Framework time format. Defaults to the library timeout. The timeout is applied to each alert separately.
There must be an equal amount of items in the actions, prompt_inputs and texts lists. Use None if texts and/or prompt inputs are not needed.
This keyword works in the same way as Wait For Alert, but it can handle multiple alerts with one promise. Like the Wait For Alert keyword, this keyword must be called as an argument to the Promise To keyword.
Example to handle two alerts, first one is accepted and second one is dismissed:
${promise} = Promise To... Wait For Alerts... ["accept", "dismiss"]... [None, None]... [None, None]Click id=alerts${texts} = Wait For ${promise}
Example to handle confirm and prompt alert. Example assumes that the first is a confirm and second one is prompt:
${promise} = Promise To... Wait For Alerts... ["dismiss", "accept"]... [None, "I am a prompt"]... ["First alert accepted?", None]Click id=confirmAndPrompt${texts} = Wait For ${promise}
Waits for a condition, defined with Browser getter keywords, to become True.
This keyword is basically just a wrapper around our assertion keywords, but with a timeout. It can be used to wait for anything that also can be asserted with our keywords.
In comparison to Robot Framework's Wait Until Keyword Succeeds this keyword is more readable and easier to use, but is limited to Browser library's assertion keywords.
Arguments
Description
condition
A condition, defined with Browser getter keywords, without the word Get.
*args
Arguments to pass to the condition keyword.
timeout
Timeout to wait for the condition to become True. Uses default timeout of the library if not set. As the other assertion keywords this timeout only influences the time the assertion is retried. The browser timeout is used to wait for the element to be found.
message
Overrides the default error message.
The easiest way to use this keyword is first starting with an assertion keyword with assertion like: Get Text
Start:
Get Text id=status_bar contains Done
Then you replace the word Get with Wait For Condition and if necessary add the timeout argument.
End:
Wait For Condition Text id=status_bar contains Done
Example usage:
Wait For Condition Element States id=cdk-overlay-0 == detachedWait For Condition Element States //h1 contains visible editable enabled timeout=2 sWait For Condition Title should start with RobotWait For Condition Url should end with robotframework.org
If users experience reliability issues with this keyword, consider using Wait for Condition with Get Element States keyword instead. Wait For Elements State uses features of Playwright to wait for element states. However, in some situations these features might not work as expected. Wait for Condition with Get Element States is more robust as it uses Browser library's own waiting mechanisms that actively poll the state of an element.
State options are appearing in or disappearing from the DOM, becoming visible or hidden, and the other states listed in ElementState. If at the moment of calling the keyword, the selector already satisfies the condition, the keyword will return immediately.
If the selector doesn't satisfy the condition within the timeout the keyword will FAIL.
Arguments
Description
selector
Selector of the corresponding object. See the Finding elements section for details about the selectors.
overrides the default error message. The message argument accepts {selector}, {function}, and {timeout}format options. The {function} formatter is the state argument value for the states which are waited for by Playwright, that are attached, detached, visible, hidden, stable, enabled, disabled and editable. For all other states, it is the JavaScript expression which is evaluated for the element.
The states focused and defocused are not supported with iframe selectors, which contain >>>. In that case the keyword raises an error and suggests to use Wait For Condition with Get Element States instead.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Example:
Wait For Elements State //h1 visible timeout=2 sWait For Elements State //h1 focused 1s
Polls JavaScript expression or function in browser until it returns a (JavaScript) truthy value.
Arguments
Description
function
A valid javascript function or a javascript function body. For example () => true and true will behave similarly.
selector
Selector to resolve and pass to the JavaScript function. This will be the first argument the function receives. If a selector is given, function must be a function with an argument which receives the element handle. For example (element) => document.activeElement === element. See the Finding elements section for details about the selectors.
polling
Default polling value of raf polls in a callback for requestAnimationFrame. Any other value for polling will be parsed as a Robot Framework time for the interval between polls.
timeout
Uses default timeout of the library if not set.
message
overrides the default error message. The message argument accepts {selector}, {function}, and {timeout}format options.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Example usage:
${promise} Promise To Wait For Function element => element.style.width=="100%" selector=\#progress_bar timeout=4sClick \#progress_barWait For ${promise}
Waits until the page reaches the required load state.
This resolves when the page reaches a required load state, load by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.
Arguments
Description
state
State to wait for, defaults to load. Possible values are load, domcontentloaded, networkidle and commit.
timeout
Timeout supports Robot Framework time format. Uses browser timeout if not set.
If the state has been already reached while loading current document, the underlying Playwright will resolve immediately. Can be one of:
load - wait for the load event to be fired.domcontentloaded - wait for the DOMContentLoaded event to be fired.networkidle - DISCOURAGED wait until there are no network connections for at least 500 ms.commit - not supported by this keyword, the keyword returns immediately without waiting.
Example:
Go To ${URL}Wait For Load State domcontentloaded timeout=3s
Waits until the page has navigated to the given url.
Arguments
Description
url
Expected navigation target address, either a Glob-Pattern (a plain string without wildcards matches exactly) or a JavaScript-like regex wrapped in / symbols.
timeout
Timeout supports Robot Framework time format. Uses default timeout if not set.
wait_until
When to consider the operation succeeded, defaults to load. Events can be either: domcontentloaded - consider operation to be finished when the DOMContentLoaded event is fired. load - consider operation to be finished when the load event is fired. networkidle - consider operation to be finished when there are no network connections for at least 500 ms. commit - consider operation to be finished when network response is received and the document started loading.
Only the request is awaited, not its response. See Wait For Response if the response is needed.
The returned object is a dictionary with the keys url, method, headers and postData. headers is a dictionary of request headers. postData is None if the request has no body, a dictionary if the body is valid JSON and otherwise the body as a string.
Arguments
Description
matcher
Request URL matcher. Can be a string (Glob-Pattern), a JavaScript RegExp (enclosed in / with optional trailing flags) or a JavaScript arrow-function that receives the Request object and returns a boolean. By default (with an empty string) the first request is matched. For additional information, see the Playwright waitForRequest documentation.
timeout
Timeout supports Robot Framework time format. Uses default timeout if not set.
CAUTION: Before Browser library 17.0.0, the matcher argument was always either a regex or JS function. But the regex did not need to be in slashes. The most simple way to migrate to the new syntax is to add slashes around the matcher. So /api/get/json becomes //api/get/json/.
Waits for a response matching matcher and returns the response as a Robot Framework dictionary.
Arguments
Name
Default
Type
matcher
=
Union
timeout
=None
Union
Returns
Union
Tags
HTTPWait
Documentation
Waits for a response matching matcher and returns the response as a Robot Framework dictionary.
The keyword waits until the response headers are received and then reads the response body.
The response, which is returned by this keyword, is a Robot Framework dictionary with the following attributes:
status <int> The status code of the response.
statusText <str> Status text corresponding to status, e.g. OK or INTERNAL SERVER ERROR. This may not be available for all browsers.
body <dict | str> The response body. If the body can be parsed as a JSON object, it will be returned as Python dictionary, otherwise it is returned as a string. It is None if the body could not be read and the key is missing altogether if the response body is empty.
headers <dict> A dictionary containing all response headers.
ok <bool> Whether the request was successful, i.e. the status is in the range 200-299.
Response URL matcher. Can be a string (Glob-Pattern), a JavaScript RegExp (enclosed in / with optional trailing flags) or a JavaScript arrow-function that receives the Response object and returns a boolean. By default (with an empty string) the first response is matched. For additional information, see the Playwright page.waitForResponse documentation.
timeout
Timeout supports Robot Framework time format. Uses default timeout if not set.
CAUTION: Before Browser library 17.0.0, the matcher argument was always either a regex or JS function. But the regex did not need to be in slashes. The most simple way to migrate to the new syntax is to add slashes around the matcher. So /api/get/json becomes //api/get/json/.
Matcher Examples:
Glob-Pattern:
Glob-Patterns are strings that can contain wildcards. Possible wildcards/patterns are:
* matches any number of characters, except /
** matches any number of characters, including /
? matches one character, except /
[abc] matches one character in the brackets (in this example a, b or c)
[a-z] matches one character in the range (in this example a to z)
{foo,bar,baz} matches one of the strings in the braces (in this example foo, bar or baz)
Example:
Wait For Response **/api/get/text # matches any response with url ending with /api/get/text. example: https://browser.fi/api/get/text
RegExp:
Regular Expressions are JavaScript regular expressions enclosed in / with optional trailing flags. Be aware that backslashes need to be escaped in Robot Framework, e.g. \\w instead of \w. See regex101 for more information on Regular Expressions.
Example:
Wait For Response /http://\\w+:\\d+/api/get/text/i # matches any response with url ending with /api/get/text and containing http:// followed by any word and port. example: http://localhost:8080/api/get/text
JavaScript Arrow-Function:
JavaScript Arrow-Functions are anonymous JavaScript functions that receive the Response object and return a boolean.
Example:
Wait For Response response => response.url() === 'http://localhost/api/post' && response.status() === 200 # matches any response with url http://localhost/api/post and status code 200
Robot Examples:
Synchronous Example:
Click \#delayed_request # Creates response which should be waited before next actionsWait For Response matcher=/http://\\w+:\\d+/api/get/text/iClick \#save
Asynchronous Example:
${promise} = Promise To Wait For Response timeout=60sClick \#delayed_request # Creates response which should be waited before pressing save.Click \#nextWait For ${promise} # Waits for the responseClick \#save
JavaScript Function Example:
Click \#delayed_request # Creates response which should be waited before pressing save.Wait For Response response => response.url().endsWith('json') && response.request().method() === 'GET'
One of a fixed set of values, written as a plain string.
Defines the mode of the AriaSnapshot.
Value
Description
default
Standard aria snapshot.
ai
Snapshot optimized for AI consumption. It includes element references like [ref=e2], includes snapshots of iframes inside the target and does not wait for a matching element, but fails immediately when no element matches.
One of a fixed set of values, written as a plain string.
Defines the return type of the AriaSnapshot.
Value
Description
dict
returns the snapshot as a dictionary.
yaml
returns the snapshot as a yaml string.
parsed
returns the snapshot as a tree of node dictionaries.
dict loads the yaml as it is. Role, name and all annotations of an element stay inside the dictionary keys, for example {'heading "Login Page" [level=1]': None}.
parsed splits that information into separate keys. Every node has role, name, text, props and children, and its values are reachable both as ${node}[role] and as ${node.role}. Annotations without a value, like [selected], become True, [level=2] becomes an integer and box uses the same keys as Get BoundingBox. The /url entry of a link is an annotation in Playwright, not an element, and therefore becomes the url property of the link instead of one of its children.
Examples
All outputs below come from the same element of the same page. It offers fourteen tag options; the examples stop after the fourth one:
New Browser chromiumNew Page https://robotframework-browser.org/keywords${snapshot} = Get Aria Snapshot .rail-top
return_type=yaml (default)
- text: Filter keywords- searchbox "Filter keywords"- group: Version 20.3.0- text: Filter by tag- combobox "Filter by tag": - option "— Show all tags —" [selected] - option "Setter (84)" - option "PageContent (83)" - option "Getter (45)"
return_type=yaml with boxes=True
- text: Filter keywords- searchbox "Filter keywords" [box=12,77,279,30]- group [box=12,116,279,34]: Version 20.3.0- text: Filter by tag- combobox "Filter by tag" [box=12,158,279,32]: - option "— Show all tags —" [selected] [box=0,0,0,0] - option "Setter (84)" [box=0,0,0,0] - option "PageContent (83)" [box=0,0,0,0] - option "Getter (45)" [box=0,0,0,0]
One of a fixed set of values, written as a plain string.
Currently supported assertion operators are:
Operator
Alternative Operators
Description
Validate Equivalent
==
equal, equals, should be
Checks if returned value is equal to expected value.
value == expected
!=
inequal, should not be
Checks if returned value is not equal to expected value.
value != expected
>
greater than
Checks if returned value is greater than expected value.
value > expected
>=
Checks if returned value is greater than or equal to expected value.
value >= expected
<
less than
Checks if returned value is less than expected value.
value < expected
<=
Checks if returned value is less than or equal to expected value.
value <= expected
*=
contains
Checks if returned value contains expected value as substring.
expected in value
not contains
Checks if returned value does not contain expected value as substring.
expected in value
^=
should start with, starts
Checks if returned value starts with expected value.
re.search(f"^{expected}", value)
$=
should end with, ends
Checks if returned value ends with expected value.
re.search(f"{expected}$", value)
matches
Checks if given RegEx matches minimum once in returned value.
re.search(expected, value)
validate
Checks if given Python expression evaluates to True.
evaluate
then
When using this operator, the keyword does return the evaluated Python expression.
There are three different possibilities what keyword returns when matches operator is used: string, tuple or dictionary. What keyword returns depends on how the RegEx is formed. If RegEx does not contain group(s), then keyword will return the string without modifications. If RegEx contains groups, meaning (...), then keyword will return a tuple. Each tuple item contains the text which is matched by the group. If there is group and group has a name, (?P<name>...) syntax, then keyword returns a dictionary. In this case dictionary key is the group name and value contains the matched text. If there mix of groups and groups with names, then tuple is returned.
Currently supported formatters for assertions are:
Formatter
Description
normalize spaces
Substitutes multiple spaces to single space from the value
strip
Removes spaces from the beginning and end of the value
case insensitive
Converts value to lower case before comparing
apply to expected
Applies rules also for the expected value
Formatters are applied to the value before assertion is performed and keywords returns a value where rule is applied. Formatter is only applied to the value which keyword returns and not all rules are valid for all assertion operators. If apply to expected formatter is defined, then formatters are then formatter are also applied to expected value.
Accepted values
equalequals==should beinequal!=should not beless than<greater than><=>=containsnot contains*=starts^=should start withendsshould end with$=matchesvalidatethenevaluate
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.
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)
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.
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.
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.
One of a fixed set of values, written as a plain string.
Emulates 'prefers-color-scheme' media feature. Supported values are 'light', 'dark', 'no-preference' and null. Passing null disables color scheme emulation. no-preference is deprecated.
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.
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.
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.
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.
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'}
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.
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.
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.
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.
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
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.
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.
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.
bypassOptional coma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com".
usernameOptional username to use if HTTP proxy requires authentication.
passwordOptional password to use if HTTP proxy requires authentication.
One of a fixed set of values, written as a plain string.
Defines which pages Set Storage State reloads while it restores the state.
Restoring a state file that contains IndexedDB does not finish while a page of the context holds an open connection to a database of that origin. To get around that, the pages are navigated to about:blank, the state is restored, and they are navigated back to the url they had before.
affected: Reloads the pages whose origin has IndexedDB in the state file. none: Reloads nothing. The keyword fails immediately when it detects an open connection which would block the restore. all: Reloads every page of the context.
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.
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.
Encapsulates secret values to avoid them being shown in Robot Framework logs.
The value is required to be robot.api.types.Secret object. These objects encapsulate confidential values so that they are not exposed in log files. How to create them is explained in the User Guide.
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.
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.
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.
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.
Strings must be Python tuple or list literals. They are converted using the ast.literal_eval function and possible lists converted further to tuples. They can contain any values ast.literal_eval supports, including tuples and other collections.
If the argument is a tuple, it is used without conversion. Lists and other sequences are converted to tuples.
If the type has nested types like tuple[str, int, int], items are converted to those types automatically.