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.6.020 modules83 argument types
Introduction
Generated from the library's Libdoc for 20.6.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.
Given url for the cookie. Defaults to None. Either url or the domain / path pair must be set, but not both.
domain
=None
Union
Given domain for the cookie. Defaults to None. Either url or the domain / path pair must be set, but not both.
path
=None
Union
Given path for the cookie. Defaults to None. Either url or the domain / path pair must be set, but not both.
expires
=None
Union
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
=None
Union
Sets the httpOnly token.
secure
=None
Union
Sets the secure token.
sameSite
=None
Union
Sets the sameSite mode. Can be Strict, Lax or None.
Tags
BrowserControlSetter
Documentation
Adds a cookie to the currently active browser context.
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.
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.
timesnamed only
=None
Union
Is how many times the locator handler is called. None, the default, means unlimited.
Whether to bypass checks and dispatch the event directly. Defaults to false.
Tags
PageContentSetter
Documentation
Add a handler function which will activate when selector is visible and click.
The handler will click the element indicated by click_selector.
When testing a web page, sometimes unexpected overlays, for example an "Accept Cookies" dialog, might appear and block the interaction with the page, like the Click keyword. These overlays can be problematic to handle, because they might appear randomly in the page. This keyword allows to create an automatic method, which will close those overlays by clicking the element indicated by click_selector. The handler is activated when the element indicated by selector is visible. For further information, see Playwright's addLocatorHandler method.
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
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
=None
Union
Is how many times the locator handler is called. None, the default, means unlimited.
Tags
PageContentSetter
Documentation
Add a handler function which will activate when selector is visible and performs handler specification.
When the element indicated by selector is visible, the handler will perform the actions specified in the handler_spec.
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;
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.
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.
position_xnamed only
=None
Union
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.
position_ynamed only
=None
Union
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.
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.
Tags
PageContentSetter
Documentation
Simulates mouse click on the element found by selector.
This keyword clicks an element matching selector by performing the following steps:
Find an element matching the selector. If there is none, wait until a matching element is attached to the DOM.
Wait for actionability checks on the matched element, unless the force option is set. If the element is detached during the checks, the whole action is retried.
Scroll the element into view if needed.
Use Mouse Button to click in the center of the element, or the specified position.
Wait for initiated navigation to either succeed or fail, unless the noWaitAfter option is set.
Arguments 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
Browser to close. CURRENT selects the active browser. ALL closes all browsers. When a browser id is provided, that browser is closed.
Tags
BrowserControlSetter
Documentation
Closes the current browser.
Active browser is set to the browser that was active before this one. Closes all context and pages belonging to this browser. See Browser, Context and Page for more information about Browser and related concepts.
Example:
Close Browser ALL # Closes all browsersClose Browser CURRENT # Close current browserClose Browser # Close current browserClose Browser ${id} # Close browser matching id
Closing is given at least 20 seconds to finish, and twice the current Set Browser Timeout value when that is longer. A browser that has stopped responding therefore fails this keyword instead of hanging the run, and a short Browser timeout does not cut the closing short.
Context to close. CURRENT selects the active context. ALL selects all contexts. When a context id is provided, that context is closed.
browser
=CURRENT
Union
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.
If set to False, the trace of this context is not saved, even if it was enabled by New Context. Defaults to True.
Tags
BrowserControlSetter
Documentation
Closes a Context.
Active context is set to the context that was active before this one. Closes pages belonging to this context. See Browser, Context and Page for more information about Context and related concepts.
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
Closing is given at least 20 seconds to finish, and twice the current Set Browser Timeout value when that is longer. A browser that has stopped responding therefore fails this keyword instead of hanging the run, and a short Browser timeout does not cut the closing short.
Page to close. CURRENT selects the active page.`ALL` selects all pages. When a page id is provided, that page is closed.
context
=CURRENT
Union
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
=CURRENT
Union
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.
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.
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
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.
Tags
BrowserControlSetter
Documentation
Connect to a Playwright browser server via playwright websocket or Chrome DevTools Protocol.
See Launch Browser Server for more information about how to launch a playwright browser server.
Returns a stable identifier for the connected browser.
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.
Arguments
Name
Default
Type
url
=None
Union
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
=take_screenshot
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.
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.
Tags
Crawling
Documentation
Web crawler is a tool to go through all the pages on a specific URL domain. This happens by finding all links going to the same site and opening those. Links pointing to another scheme or host are ignored, as are download links.
Returns the list of crawled urls. The order of the returned urls is not guaranteed to be the order in which the pages were crawled.
Relying party id (typically the site's effective domain).
id_
=None
Union
Base64url-encoded credential id. Auto-generated if omitted.
privateKey
=None
Union
Base64url-encoded PKCS#8 (DER) private key. Auto-generated if omitted.
publicKey
=None
Union
Base64url-encoded SPKI (DER) public key. Auto-generated if omitted.
userHandle
=None
Union
Base64url-encoded user handle. Auto-generated if omitted.
Tags
CredentialSetter
Documentation
Creates a credential with the given parameters.
Will always https://playwright.dev/docs/api/class-credentials#credentials-create and https://playwright.dev/docs/api/class-credentials#credentials-install the credential, even if the optional parameters are not provided. In this case Playwright will autogenerate the missing values.
The credential is created in the currently active context and it is used by all pages that are created from that context. There must be an open context, otherwise the keyword fails.
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
Selector of the select tag. See the Finding elements section for details about the selectors.
Tags
PageContentSetter
Documentation
Deselects all options from select element found by selector.
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.
If set to False keyword returns immediately after the download has started. Defaults to True.
download_timeout
=None
Union
Maximum total time for the file to be fetched and saved. If the file is not fetched within this time, the keyword fails. If it is fetched but not saved, the download is cancelled and the keyword fails. If wait_for_finished is False, only the fetching is limited. If not set, the file must be fetched within the browser timeout, see Set Browser Timeout, and there is no limit for saving it.
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.
The whole file is fetched before the browser reports the download as started. Set download_timeout when fetching the file can take longer than the browser timeout, for example with large files or slow servers.
Example:
${file_object}= Download ${url} download_timeout=2 minutes${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
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.
Tags
PageContentSetter
Documentation
Executes a Drag&Drop operation from the element selected by selector_from to the element selected by selector_to.
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.
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.
Tags
PageContentSetter
Documentation
Executes a Drag&Drop operation from a coordinate to another coordinate.
First it moves the mouse to the start-point, then presses the left mouse button, then moves to the end-point in specified number of steps, then releases the mouse button.
Start- and end-point are defined by x and y coordinates relative to the top left corner of the pages viewport.
Example:
Drag And Drop By Coordinates... from_x=30 from_y=30... to_x=10 to_y=10 steps=20
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.
Tags
PageContentSetter
Documentation
Executes a Drag&Drop operation from the element selected by selector_from to coordinates relative to the center of that element.
This keyword can be handy to simulate swipe actions.
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
Emulates the prefers-color-scheme media feature, supported values are light and dark. Passing null disables color scheme emulation. no-preference is deprecated.
forcedColors
=not_set
Union
Emulates the forced-colors media feature, supported values are active and none. Passing null disables forced colors emulation.
media
=None
Union
Changes the CSS media type of the page. The only allowed values are screen, print and null. Passing null disables CSS media emulation.
reducedMotion
=None
Union
Emulates the prefers-reduced-motion media feature, supported values are reduce and no-preference. Passing null disables reduced motion emulation.
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 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.
Arguments
Name
Default
Type
selector
=None
Union
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
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.
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.
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.
Selector of the text field. See the Finding elements section for details about the selectors.
secretrequired
Union
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).
Fills the given secret into the text field found by selector.
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.
Keyword uses strict mode, see Finding elements for more details about strict mode.
See Type Text for emulating typing text character by character.
Selector of the element. See the Finding elements section for details about the selectors.
Tags
PageContentSetter
Documentation
Moves focus on to the element found by selector.
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.
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
=None
Union
See Assertions for further details. Defaults to None.
assertion_expected
=None
Union
Expected value for the state
message
=None
Union
overrides the default error message for assertion.
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.
Returns
Union
Tags
AssertionGetterPageContent
Documentation
Returns the aria snapshot of the element found by selector. See AriaSnapshotReturnType for more details and examples.
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}
See Assertions for further details. Defaults to None.
assertion_expected
=None
Union
Expected value for the state
message
=None
Union
overrides the default error message for assertion.
Returns
Union
Tags
AssertionGetterPageContent
Documentation
Returns the HTML attribute of the element found by selector.
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.
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.
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
=None
Union
See Assertions for further details. Defaults to None.
assertion_expected
=None
Union
Expected value for the assertion
message
=None
Union
overrides the default error message for assertion.
(named only) If True, hidden elements are not causing a failure and will return None. Otherwise a hidden element will fail. Defaults to False.
Returns
Union
Tags
AssertionGetterPageContent
Documentation
Gets elements size and location as an object {x: float, y: float, width: float, height: float}.
Alternatively you can select a single attribute of the bounding box by setting the key argument.
If an element is hidden and has no bounding box, the keyword will fail. Depending on the method used to make an element invisible, an element might still have a bounding box which can be retrieved. To allow also hidden elements without a bounding box, set allow_hidden to True, which results in a return value of None in case of no bounding box.
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
Selector which shall be examined. See the Finding elements section for details about the selectors.
assertion_operator
=None
Union
== and != and equivalent are allowed on boolean values. Other operators are not accepted.
assertion_expected
=Unchecked
Union
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
=None
Union
overrides the default error message for assertion.
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.
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
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
Name
Default
Type
selector
=None
Union
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.
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
=None
Union
See Assertions for further details. Defaults to None.
assertion_expected
=None
Union
Expected value for the assertion
message
=None
Union
overrides the default error message for assertion.
Returns
Union
Tags
AssertionGetterPageContent
Documentation
Gets elements or pages client size (clientHeight, clientWidth) as object {width: float, height: float}.
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.
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
=ALL
Union
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.
Type of the return value. Can be either dictionary or string. Defaults to dictionary.
Returns
Union
Tags
BrowserControlGetter
Documentation
Returns information about the cookie named cookie as a Robot Framework dot dictionary or a string.
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.
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
Returns a single device descriptor whose name matches name exactly.
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.
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.
An attribute that is usually set by aria-checked or native <input type=checkbox> controls.
disablednamed only
=None
Union
An attribute that is usually set by aria-disabled or disabled.
exactnamed only
=None
Union
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.
expandednamed only
=None
Union
An attribute that is usually set by aria-expanded.
include_hiddennamed only
=None
Union
Option that controls whether hidden elements are matched. By default, only non-hidden elements, as defined by ARIA, are matched by role selector.
levelnamed only
=None
Union
A number attribute that is usually present for roles heading, list item, row, treeitem, with default values for <h1>-<h6> elements.
namenamed only
=None
Union
Option to match the accessible name. By default, matching is case-insensitive and searches for a substring, use exact to control this behavior.
pressednamed only
=None
Union
An attribute that is usually set by aria-pressed.
selectednamed only
=None
Union
An attribute that is usually set by aria-selected.
${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
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.
Optionally asserts that the count matches the specified assertion. See Assertions for further details for the assertion arguments. By default assertion is not done.
Selector of the corresponding object. See the Finding elements section for details about the selectors.
assertion_operator
=None
Union
See Assertions for further details. Defaults to None.
*assertion_expected
Union
Expected states
messagenamed only
=None
Union
overrides the default error message for assertion.
return_namesnamed only
=True
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.
Returns
Union
Tags
AssertionGetterPageContent
Documentation
Get the active states from the element found by selector.
This Keyword returns a list of states that are valid for the selected element.
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.
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
=ALL
Union
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
=ALL
Union
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.
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.
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.
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}.
Arguments
Name
Default
Type
selector
=None
Union
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.
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
=None
Union
See Assertions for further details. Defaults to None.
assertion_expected
=None
Union
Expected value for the assertion
message
=None
Union
overrides the default error message for assertion.
Returns
Union
Tags
AssertionGetterPageContent
Documentation
Gets elements or pages current scroll position as object {top: float, left: float, bottom: float, right: float}.
It describes the rectangle which is visible of the scrollable content of that element. All values are measured from position {top: 0, left: 0}.
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
Name
Default
Type
selector
=None
Union
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.
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
=None
Union
See Assertions for further details. Defaults to None.
assertion_expected
=None
Union
Expected value for the assertion
message
=None
Union
overrides the default error message for assertion.
Returns
Union
Tags
AssertionGetterPageContent
Documentation
Gets elements or pages scrollable size as object {width: float, height: float}.
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".
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.
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
Selector from which the style shall be retrieved. See the Finding elements section for details about the selectors.
key
=ALL
Union
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
=None
Union
See Assertions for further details. Defaults to None.
assertion_expected
=None
Union
Expected value for the assertion
message
=None
Union
overrides the default error message for assertion.
pseudo_element
=None
Union
Pseudo element to match. Defaults to None.
Returns
Union
Tags
AssertionGetterPageContent
Documentation
Gets the computed style properties of the element selected by selector.
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.
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.
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.
${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.
Selector from which the text is to be retrieved. See the Finding elements section for details about the selectors.
assertion_operator
=None
Union
See Assertions for further details. Defaults to None.
assertion_expected
=None
Union
Expected value for the state
message
=None
Union
overrides the default error message for assertion.
text_typenamed only
=None
Union
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.
Returns
Union
Tags
AssertionGetterPageContent
Documentation
Returns text attribute of the element found by selector.
Keyword can also return the value property text of input or textarea elements. See the Finding elements section for details about the selectors.
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
=None
Union
Expected value for the state
message
=None
Union
overrides the default error message for assertion.
Returns
Union
Tags
AssertionGetterPageContent
Documentation
Returns the title of the current page.
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
=None
Union
Expected value for the state
message
=None
Union
overrides the default error message for assertion.
Returns
Union
Tags
AssertionGetterPageContent
Documentation
Returns the current URL.
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
=None
Union
See Assertions for further details. Defaults to None.
assertion_expected
=None
Union
Expected value for the assertion
message
=None
Union
overrides the default error message for assertion.
Returns
Union
Tags
AssertionBrowserControlGetter
Documentation
Returns the current viewport dimensions.
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
If the wait times out, the page's load report is logged: whether its navigation committed, how far the document got and which requests were still open.
If the wait times out, the page's load report is logged: whether its navigation committed, how far the document got and which requests were still open.
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.
Tags
BrowserControlSetter
Documentation
Navigates to the given url.
Returns the HTTP status code of the navigation request as an integer, or 0 if no response was received.
If the wait times out, the page's load report is logged: whether its navigation committed, how far the document got and which requests were still open.
Permissions to grant, given as separate arguments. See Permission for the available values, for example geolocation, notifications, camera or microphone.
originnamed only
=None
Union
The origin to grant the permissions to, e.g. "https://example.com". If not given, the permissions are granted for all origins.
The value to enter into the prompt. Only valid if the action argument equals accept. Defaults to an empty string.
Tags
PageContent
Documentation
Handle next dialog on page with action.
The dialog can be an alert, beforeunload, confirm or prompt dialog. This keyword must be called before the action, for example a click, which triggers the dialog.
The handler is registered on the current page and stays in effect for all following dialogs on that page. Calling this keyword again on the same page replaces the handler, so the latest call decides how dialogs are handled.
If a handler is not set, dialogs are dismissed by default.
The handler runs when the dialog appears, not while this keyword executes, so a failure to accept or dismiss the dialog can not be raised as a keyword failure. Such a failure is reported in the playwright-log.txt file only, which is linked into the Robot Framework log when a keyword fails.
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.
Tags
PageContentSetter
Documentation
Adds a highlight to elements matched by the selector. Provides a style adjustment.
Returns the number of highlighted elements. Keyword does not fail, if the selector matched zero elements in the page. Keyword does not scroll elements to viewport and highlighted element might be outside the viewport. Use Scroll To Element keyword to scroll element in viewport.
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}
Selector element to hover. See the Finding elements section for details about the selectors.
position_x
=None
Union
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.
position_y
=None
Union
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.
Tags
PageContentSetter
Documentation
Moves the virtual mouse and scrolls to the element found by selector.
This method hovers over an element matching selector by performing the following steps:
Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
Wait for actionability checks on the matched element, unless the force option is set. If the element is detached during the checks, the whole action is retried.
Scroll the element into view if needed.
Use Mouse Move to hover over the center of the element, or the specified position.
Keyword uses strict mode, see Finding elements for more details about strict mode.
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
=None
Union
A dictionary of additional request headers. Defaults to None.
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.
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.
The input string to be typed. No special keys possible.
delay
=0:00:00
Union
Time to wait between key presses in Robot Framework's time format. Defaults to 0 ms.
Tags
PageContentSetter
Documentation
Input text into page with virtual keyboard.
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
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.
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
Tags
PageContentSetter
Documentation
Press a keyboard key on the virtual keyboard or set a key up or down.
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.
Combines multiple raw coverage reports into a single report.
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
Determines how often the button shall be clicked if action is equal to click. Defaults to 1.
delay
=0:00:00
Union
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.
Tags
PageContentSetter
Documentation
Clicks, presses or releases a mouse button.
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
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.
Tags
PageContentSetter
Documentation
Moves the virtual mouse to the given coordinates, instead of to an element found by a selector.
The virtual mouse is left on the specified coordinates.
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.
Tags
PageContentSetter
Documentation
Moves the mouse cursor relative to the selected element.
Keyword uses strict mode, see Finding elements for more details about strict mode.
Additional arguments to pass to the browser instance. The list of Chromium flags can be found here. Defaults to None.
channelnamed only
=None
Union
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.
Chromium-only. Whether to auto-open a Developer Tools panel for each tab. Defaults to False.
downloadsPathnamed only
=None
Union
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.
envnamed only
=None
Union
Specifies environment variables that will be visible to the browser. Dictionary keys are variable names, values are the content. Defaults to None.
executablePathnamed only
=None
Union
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.
firefoxUserPrefsnamed only
=None
Union
Firefox user preferences. Learn more about the Firefox user preferences at about:config.
Close the browser process on SIGTERM. Defaults to True.
ignoreDefaultArgsnamed only
=None
Union
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.
proxynamed only
=None
Union
Network Proxy settings. Structure: {'server': <str>, 'bypass': <Optional[str]>, 'username': <Optional[str]>, 'password': <Optional[str]>}. Robot Framework 7.4 Secret type is supported.`
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.
Whether to automatically download all the attachments. Defaults to True where all the downloads are accepted.
baseURLnamed only
=None
Union
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.
Toggles bypassing page's Content-Security-Policy. Defaults to False.
clientCertificatesnamed only
=None
Union
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.
colorSchemenamed only
=None
Union
Emulates the prefers-color-scheme media feature, supported values are light, dark, no-preference and null. null disables the emulation.
defaultBrowserTypenamed only
=None
Union
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.
deviceScaleFactornamed only
=None
Union
Specify device scale factor (can be thought of as dpr). Defaults to 1.
extraHTTPHeadersnamed only
=None
Union
A dictionary containing additional HTTP headers to be sent with every request. All header values must be strings.
Emulates the forced-colors media feature, supported values are active, none and null. Defaults to none.
geolocationnamed only
=None
Union
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.
hasTouchnamed only
=None
Union
Specifies if viewport supports touch events. Defaults to False.
Toggles browser's offline mode. Defaults to False.
permissionsnamed only
=None
Union
A list containing permissions to grant to all pages in this context. All permissions that are not listed here will be automatically denied.
proxynamed only
=None
Union
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' }.
recordHarnamed only
=None
Union
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.
recordVideonamed only
=None
Union
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.
Emulates the prefers-reduced-motion media feature, supported values are reduce and no-preference. Defaults to no-preference.
screennamed only
=None
Union
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}
serviceWorkersnamed only
=allow
Union
Whether to allow sites to register Service workers. Defaults to allow.
storageStatenamed only
=None
Union
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.
timezoneIdnamed only
=None
Union
Changes the timezone of the context. See ICU metaZones.txt for a list of supported timezone IDs.
tracingnamed only
=None
Union
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.
userAgentnamed only
=None
Union
Specific user agent to use in this context.
viewportnamed only
={'width': 1280, 'height': 720}
Union
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.
Returns a stable identifier for the created context that can be used in Switch Context.
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
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.
A Page is the Playwright equivalent to a tab. See Browser, Context and Page for more information about Page concept.
Returns NewPageDetails as dictionary for created page. NewPageDetails (dict) contains the keys page_id and video_path. page_id is a stable identifier for the created page. video_path is path to the created video or empty if video is not created.
If navigating to url fails, the keyword fails and the newly created page is closed again. The page is closed only after the keyword set with Register Keyword To Run On Failure has run, so the failure screenshot shows the page that failed to load.
If the wait times out, the page's load report is logged: whether its navigation committed, how far the document got and which requests were still open.
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.
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.
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
Keyword that will run asynchronously in the background.
*args
Keyword arguments as normally used.
Returns
Future
Tags
Wait
Documentation
Wrap a Browser library keyword and make it a promise.
The promised keyword is started in the background. Test execution continues without waiting for kw to finish.
Returns a reference to the promised keyword. Use Wait For or Wait For All Promises to wait for its result. Promises that are never waited for are waited for automatically at the end of the test, and a warning is logged.
Only Browser library keywords can be promised, any other keyword name fails the keyword.
Example:
${promise}= Promise To Wait For Response matcher= timeout=3Click \#delayed_request${body}= Wait For ${promise}
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.
If true, promise will wait for download to finish. If false, promise will resolve immediately after download has started.
download_timeout
=None
Union
Maximum total time for the download to start and finish, counted from the moment the promise is created. If the download does not start within this time, the keyword fails. If it starts but does not finish, it is cancelled and the keyword fails. If wait_for_finished is False, only the start is limited. If not set, the download must start within the browser timeout, see Set Browser Timeout, and there is no limit for it to finish.
Returns
Future
Tags
BrowserControlWait
Documentation
Returns a promise that waits for the next download event on the page.
To enable downloads the context's acceptDownloads needs to be true.
With the default file path downloaded files are deleted when the context the download happened in is closed.
If browser is connected remotely with Connect To Browser then saveAs must be set to store it locally where the browser runs!
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.
Set download_timeout when the download can take longer than the browser timeout, for example when the server generates the file before sending it.
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.name download_timeout=30sClick 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
Name
Default
Type
keywordrequired
Union
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.
Scope defines the lifetime of this setting. Available values are Global, Suite or Test / Task. See Scope Setting for more details.
Returns
DelayedKeyword
Tags
Config
Documentation
Sets the keyword to execute, when a Browser keyword fails.
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
When to consider the operation succeeded, defaults to load.
Tags
BrowserControlSetter
Documentation
Reloads current active page.
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.
If the wait times out, the page's load report is logged: whether its navigation committed, how far the document got and which requests were still open.
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.
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.
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.
Arguments
Name
Default
Type
path
=None
Union
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.
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.
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.
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
Name
Default
Type
selector
=None
Union
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.
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.
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.
Scrolls an element or the page to an absolute position based on given coordinates.
Arguments
Name
Default
Type
selector
=None
Union
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.
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.
Selects options from select element found by selector.
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.
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.
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
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.
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.
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.
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.
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
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
=None
Union
Time to wait for the state to be restored. If not defined, the library default timeout is used. Pass 0 to disable the timeout.
Which pages are reloaded while the state is restored, see ReloadPages. Only relevant when the state file contains IndexedDB.
Tags
BrowserControlSetter
Documentation
Restores a storage state file into the current active context.
Clears the cookies, local storage, IndexedDB and virtual WebAuthn credentials of the currently active context and replaces them with the ones from the path file, which must have been created by Save Storage State. Unlike creating a New Context with the storageState argument, the context and all of its pages stay open.
Pages that are already open keep the state they have loaded into memory. Reload them, with the Reload keyword, to make them see the restored state. Cookies and local storage are readable right away, without a reload, but the application has read them long ago.
Note that sessionStorage is not part of a storage state, neither when saving nor when restoring. It survives this keyword unchanged, so an application which keeps data of the previous user there still has it after the state was replaced.
Restoring a state which was saved with credentials=True installs the virtual WebAuthn authenticator into the context, the same way Install Credential does. Real authenticators do not work in that context afterwards.
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 defines the live time of that setting. Available values are Global, Suite or Test / Task. See Scope for more details.
Tags
BrowserControlSetter
Documentation
Controls library strict mode.
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}
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.
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.
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)
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.
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.
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
=CURRENT
Union
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.
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.
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.
Arguments
Name
Default
Type
idrequired
Union
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
=CURRENT
Union
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
=CURRENT
Union
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.
Takes a screenshot of the current window or element and saves it to disk.
Arguments
Name
Default
Type
filename
=robotframework-browser-screenshot-{index}
Union
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
=None
Union
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.
cropnamed only
=None
Union
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.
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.
When True, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to False.
highlight_selectornamed only
=None
Union
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.
When set to False the screenshot is taken but not logged into log.html.
masknamed only
=
Union
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.
maskColornamed only
=None
Union
Specify the color of the overlay box for masked elements, in CSS color format. Default color is pink #FF00FF.
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.
timeoutnamed only
=None
Union
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.
Returns
Union
Tags
PageContent
Documentation
Takes a screenshot of the current window or element and saves it to disk.
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.
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.
Deprecated. This option has no effect. Defaults to False.
position_xnamed only
=None
Union
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.
position_ynamed only
=None
Union
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.
Selector of the text field. See the Finding elements section for details about the selectors.
secretrequired
Union
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 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
Set to False if the field should not be cleared before typing. Defaults to True.
Tags
PageContentSetter
Documentation
Types the given secret into the text field found by selector.
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.
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
Additional paths to files or folders to be uploaded.
Tags
PageContentSetter
Documentation
Uploads file from path to file input element matched by selector.
Fails if the upload is not done before the library timeout. Therefore it may be necessary to increase the timeout with Set Browser Timeout. It is possible to upload multiple files or folders by defining additional files or folders in extra_paths.
If a path is a directory, all files from the directory are uploaded. Subdirectories are not included. It is possible to upload files and directories with the same keyword. The keyword fails if a given path does not exist.
Keyword uses strict mode, see Finding elements for more details about strict mode.
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
Promises to wait for.
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.
The value to enter into the prompt. Only valid if the action argument equals accept. Defaults to an empty string.
text
=None
Union
Optional text to verify the dialog text with.
timeout
=None
Union
Optional timeout in Robot Framework time format. Defaults to the library timeout.
Tags
PageContentWait
Documentation
Returns a promise to wait for next dialog on page, handles it with action and optionally verifies the dialogs text.
Dialog/alert can be any of alert, beforeunload, confirm or prompt.
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.
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}
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.
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.
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
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.
Tags
PageContentWait
Documentation
Waits for the element found by selector to satisfy state option.
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.
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
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
=raf
Union
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
=None
Union
Uses default timeout of the library if not set.
message
=None
Union
overrides the default error message. The message argument accepts {selector}, {function}, and {timeout}format options.
Tags
PageContentWait
Documentation
Polls JavaScript expression or function in browser until it returns a (JavaScript) truthy value.
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}
State to wait for, defaults to load. Possible values are load, domcontentloaded, networkidle and commit.
timeout
=None
Union
Timeout supports Robot Framework time format. Uses browser timeout if not set.
Tags
PageContentWait
Documentation
Waits until the page reaches the required load state.
This resolves when the page reaches a required load state, load by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.
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.
If the wait times out, the page's load report is logged: whether its navigation committed, how far the document got and which requests were still open.
Example:
Go To ${URL}Wait For Load State domcontentloaded timeout=3s
Waits until the page has navigated to the given url.
Arguments
Name
Default
Type
urlrequired
Union
Expected navigation target address, either a Glob-Pattern (a plain string without wildcards matches exactly) or a JavaScript-like regex wrapped in / symbols.
timeout
=None
Union
Timeout supports Robot Framework time format. Uses default timeout if not set.
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.
Tags
HTTPWait
Documentation
Waits until the page has navigated to the given url.
Go To ${ROOT_URL}/redirector.htmlWait for navigation ${ROOT_URL}/posted.html wait_until=${wait_until}
If the wait times out, the page's load report is logged: whether its navigation committed, how far the document got and which requests were still open.
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
=None
Union
Timeout supports Robot Framework time format. Uses default timeout if not set.
Returns
Union
Tags
HTTPWait
Documentation
Waits for a request matching matcher to be made.
Only the request is awaited, not its response. See Wait For Response if the response is needed.
The returned object is a dictionary with the keys url, method, headers and postData. headers is a dictionary of request headers. postData is None if the request has no body, a dictionary if the body is valid JSON and otherwise the body as a string.
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
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
=None
Union
Timeout supports Robot Framework time format. Uses default timeout if not set.
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.
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.