Python API
Browser.Selenium
- class RPA.Browser.Selenium.Selenium(*args, **kwargs)
SeleniumLibrary is a web testing library for Robot Framework.
This document explains how to use keywords provided by SeleniumLibrary. For information about installation, support, and more, please visit the [https://github.com/robotframework/SeleniumLibrary|project pages]. For more information about Robot Framework, see http://robotframework.org.
SeleniumLibrary uses the Selenium WebDriver modules internally to control a web browser. See http://seleniumhq.org for more information about Selenium in general and SeleniumLibrary README.rst [https://github.com/robotframework/SeleniumLibrary#browser-drivers|Browser drivers chapter] for more details about WebDriver binary installation.
%TOC%
= Locating elements =
All keywords in SeleniumLibrary that need to interact with an element on a web page take an argument typically named
locatorthat specifies how to find the element. Most often the locator is given as a string using the locator syntax described below, but using WebElements is possible too.== Locator syntax ==
SeleniumLibrary supports finding elements based on different strategies such as the element id, XPath expressions, or CSS selectors. The strategy can either be explicitly specified with a prefix or the strategy can be implicit.
=== Default locator strategy ===
By default, locators are considered to use the keyword specific default locator strategy. All keywords support finding elements based on
idandnameattributes, but some keywords support additional attributes or other values that make sense in their context. For example, Click Link supports thehrefattribute and the link text and addition to the normalidandname.Examples:
Click Element | example | # Match based onidorname. |Click Link | example | # Match also based on link text andhref. |Click Button | example | # Match based onid,nameorvalue. |If a locator accidentally starts with a prefix recognized as explicit locator strategy or implicit XPath strategy, it is possible to use the explicit
defaultprefix to enable the default strategy.Examples:
Click Element | name:foo | # Find element with namefoo. |Click Element | default:name:foo | # Use default strategy with valuename:foo. |Click Element | //foo | # Find element using XPath//foo. |Click Element | default: //foo | # Use default strategy with value//foo. |=== Explicit locator strategy ===
The explicit locator strategy is specified with a prefix using either syntax
strategy:valueorstrategy=value. The former syntax is preferred because the latter is identical to Robot Framework’s [http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#named-argument-syntax| named argument syntax] and that can cause problems. Spaces around the separator are ignored, soid:foo,id: fooandid : fooare all equivalent.Locator strategies that are supported by default are listed in the table below. In addition to them, it is possible to register custom locators.
= Strategy = | = Match based on = | = Example = |id | Elementid. |id:example|name |nameattribute. |name:example|identifier | Eitheridorname. |identifier:example|class | Elementclass. |class:example|tag | Tag name. |tag:div|xpath | XPath expression. |xpath://div[@id="example"]|css | CSS selector. |css:div#example|dom | DOM expression. |dom:document.images[5]|link | Exact text a link has. |link:The example|partial link | Partial link text. |partial link:he ex|sizzle | Sizzle selector deprecated. |sizzle:div.example|data | Elementdata-*attribute |data:id:my_id|jquery | jQuery expression. |jquery:div.example|default | Keyword specific default behavior. |default:example|See the Default locator strategy section below for more information about how the default strategy works. Using the explicit
defaultprefix is only necessary if the locator value itself accidentally matches some of the explicit strategies.Different locator strategies have different pros and cons. Using ids, either explicitly like
id:fooor by using the default locator strategy simply likefoo, is recommended when possible, because the syntax is simple and locating elements by id is fast for browsers. If an element does not have an id or the id is not stable, other solutions need to be used. If an element has a unique tag name or class, usingtag,classorcssstrategy liketag:h1,class:exampleorcss:h1.exampleis often an easy solution. In more complex cases using XPath expressions is typically the best approach. They are very powerful but a downside is that they can also get complex.Examples:
Click Element | id:foo | # Element with id ‘foo’. |Click Element | css:div#foo h1 | # h1 element under div with id ‘foo’. |Click Element | xpath: //div[@id=”foo”]//h1 | # Same as the above using XPath, not CSS. |Click Element | xpath: //*[contains(text(), “example”)] | # Element containing text ‘example’. |NOTE:
The
strategy:valuesyntax is only supported by SeleniumLibrary 3.0 and newer.Using the
sizzlestrategy or its aliasjqueryrequires that the system under test contains the jQuery library.Prior to SeleniumLibrary 3.0, table related keywords only supported
xpath,cssandsizzle/jquerystrategies.datastrategy is conveniance locator that will construct xpath from the parameters. If you have element like <div data-automation=”automation-id-2”>, you locate the element viadata:automation:automation-id-2. This feature was added in SeleniumLibrary 5.2.0
=== Implicit XPath strategy ===
If the locator starts with
//or multiple opening parenthesis in front of the//, the locator is considered to be an XPath expression. In other words, using//divis equivalent to using explicitxpath://divand((//div))is equivalent to using explicitxpath:((//div))Examples:
Click Element | //div[@id=”foo”]//h1 |Click Element | (//div)[2] |The support for the
(//prefix is new in SeleniumLibrary 3.0. Supporting multiple opening parenthesis is new in SeleniumLibrary 5.0.=== Chaining locators ===
It is possible chain multiple locators together as single locator. Each chained locator must start with locator strategy. Chained locators must be separated with single space, two greater than characters and followed with space. It is also possible mix different locator strategies, example css or xpath. Also a list can also be used to specify multiple locators. This is useful, is some part of locator would match as the locator separator but it should not. Or if there is need to existing WebElement as locator.
Although all locators support chaining, some locator strategies do not abey the chaining. This is because some locator strategies use JavaScript to find elements and JavaScript is executed for the whole browser context and not for the element found be the previous locator. Chaining is supported by locator strategies which are based on Selenium API, like xpath or css, but example chaining is not supported by sizzle or `jquery
Examples: | Click Element | css:.bar >> xpath://a | # To find a link which is present after an element with class “bar” |
List examples: | ${locator_list} = | Create List | css:div#div_id | xpath://*[text(), “ >> “] | | Page Should Contain Element | ${locator_list} | | | | ${element} = | Get WebElement | xpath://*[text(), “ >> “] | | | ${locator_list} = | Create List | css:div#div_id | ${element} | | Page Should Contain Element | ${locator_list} | | |
Chaining locators in new in SeleniumLibrary 5.0
== Using WebElements ==
In addition to specifying a locator as a string, it is possible to use Selenium’s WebElement objects. This requires first getting a WebElement, for example, by using the Get WebElement keyword.
${elem} = | Get WebElement | id:example |Click Element | ${elem} | |== Custom locators ==
If more complex lookups are required than what is provided through the default locators, custom lookup strategies can be created. Using custom locators is a two part process. First, create a keyword that returns a WebElement that should be acted on:
Custom Locator Strategy | [Arguments] | ${browser} | ${locator} | ${tag} | ${constraints} || ${element}= | Execute Javascript | return window.document.getElementById(‘${locator}’); || RETURN | ${element} |This keyword is a reimplementation of the basic functionality of the
idlocator where${browser}is a reference to a WebDriver instance and${locator}is the name of the locator strategy. To use this locator, it must first be registered by using the Add Location Strategy keyword:Add Location Strategy | custom | Custom Locator Strategy |The first argument of Add Location Strategy specifies the name of the strategy and it must be unique. After registering the strategy, the usage is the same as with other locators:
Click Element | custom:example |See the Add Location Strategy keyword for more details.
= Browser and Window =
There is different conceptual meaning when SeleniumLibrary talks about windows or browsers. This chapter explains those differences.
== Browser ==
When Open Browser or Create WebDriver keyword is called, it will create a new Selenium WebDriver instance by using the [https://www.seleniumhq.org/docs/03_webdriver.jsp|Selenium WebDriver] API. In SeleniumLibrary terms, a new browser is created. It is possible to start multiple independent browsers (Selenium Webdriver instances) at the same time, by calling Open Browser or Create WebDriver multiple times. These browsers are usually independent of each other and do not share data like cookies, sessions or profiles. Typically when the browser starts, it creates a single window which is shown to the user.
== Window ==
Windows are the part of a browser that loads the web site and presents it to the user. All content of the site is the content of the window. Windows are children of a browser. In SeleniumLibrary browser is a synonym for WebDriver instance. One browser may have multiple windows. Windows can appear as tabs, as separate windows or pop-ups with different position and size. Windows belonging to the same browser typically share the sessions detail, like cookies. If there is a need to separate sessions detail, example login with two different users, two browsers (Selenium WebDriver instances) must be created. New windows can be opened example by the application under test or by example Execute Javascript keyword:
Execute Javascript window.open() # Opens a new window with location about:blankThe example below opens multiple browsers and windows, to demonstrate how the different keywords can be used to interact with browsers, and windows attached to these browsers.
Structure: | BrowserA | Window 1 (location=https://robotframework.org/) | Window 2 (location=https://robocon.io/) | Window 3 (location=https://github.com/robotframework/) | | BrowserB | Window 1 (location=https://github.com/)
Example: | Open Browser | https://robotframework.org | ${BROWSER} | alias=BrowserA | # BrowserA with first window is opened. | | Execute Javascript | window.open() | | | # In BrowserA second window is opened. | | Switch Window | locator=NEW | | | # Switched to second window in BrowserA | | Go To | https://robocon.io | | | # Second window navigates to robocon site. | | Execute Javascript | window.open() | | | # In BrowserA third window is opened. | | ${handle} | Switch Window | locator=NEW | | # Switched to third window in BrowserA | | Go To | https://github.com/robotframework/ | | | # Third windows goes to robot framework github site. | | Open Browser | https://github.com | ${BROWSER} | alias=BrowserB | # BrowserB with first windows is opened. | | ${location} | Get Location | | | # ${location} is: https://www.github.com | | Switch Window | ${handle} | browser=BrowserA | | # BrowserA second windows is selected. | | ${location} | Get Location | | | # ${location} = https://robocon.io/ | | @{locations 1} | Get Locations | | | # By default, lists locations under the currectly active browser (BrowserA). | | @{locations 2} | Get Locations | browser=ALL | | # By using browser=ALL argument keyword list all locations from all browsers. |
The above example, @{locations 1} contains the following items: https://robotframework.org/, https://robocon.io/ and https://github.com/robotframework/’. The @{locations 2} contains the following items: https://robotframework.org/, https://robocon.io/, https://github.com/robotframework/’ and ‘https://github.com/.
= Browser and Driver options and service class =
This section talks about how to configure either the browser or the driver using the options and service arguments of the Open Browser keyword.
== Configuring the browser using the Selenium Options ==
As noted within the keyword documentation for Open Browser, its
optionsargument accepts Selenium options in two different formats: as a string and as Python object which is an instance of the Selenium options class.=== Options string format ===
The string format allows defining Selenium options methods or attributes and their arguments in Robot Framework test data. The method and attributes names are case and space sensitive and must match to the Selenium options methods and attributes names. When defining a method, it must be defined in a similar way as in python: method name, opening parenthesis, zero to many arguments and closing parenthesis. If there is a need to define multiple arguments for a single method, arguments must be separated with comma, just like in Python. Example: add_argument(”–headless”) or add_experimental_option(“key”, “value”). Attributes are defined in a similar way as in Python: attribute name, equal sign, and attribute value. Example, headless=True. Multiple methods and attributes must be separated by a semicolon. Example: add_argument(”–headless”);add_argument(”–start-maximized”).
Arguments allow defining Python data types and arguments are evaluated by using Python [https://docs.python.org/3/library/ast.html#ast.literal_eval|ast.literal_eval]. Strings must be quoted with single or double quotes, example “value” or ‘value’. It is also possible to define other Python builtin data types, example True or None, by not using quotes around the arguments.
The string format is space friendly. Usually, spaces do not alter the defining methods or attributes. There are two exceptions. In some Robot Framework test data formats, two or more spaces are considered as cell separator and instead of defining a single argument, two or more arguments may be defined. Spaces in string arguments are not removed and are left as is. Example add_argument ( “–headless” ) is same as add_argument(”–headless”). But add_argument(” –headless “) is not same same as add_argument ( “–headless” ), because spaces inside of quotes are not removed. Please note that if options string contains backslash, example a Windows OS path, the backslash needs escaping both in Robot Framework data and in Python side. This means single backslash must be writen using four backslash characters. Example, Windows path: “C:pathtoprofile” must be written as “C:\\path\to\\profile”. Another way to write backslash is use Python [https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals|raw strings] and example write: r”C:\path\to\profile”.
=== Selenium Options as Python class ===
As last format,
optionsargument also supports receiving the Selenium options as Python class instance. In this case, the instance is used as-is and the SeleniumLibrary will not convert the instance to other formats. For example, if the following code return value is saved to ${options} variable in the Robot Framework data: | options = webdriver.ChromeOptions() | options.add_argument(’–disable-dev-shm-usage’) | return optionsThen the ${options} variable can be used as an argument to
options.Example the
optionsargument can be used to launch Chomium-based applications which utilize the [https://bitbucket.org/chromiumembedded/cef/wiki/UsingChromeDriver|Chromium Embedded Framework] . To launch Chromium-based application, useoptionsto define binary_location attribute and use add_argument method to define remote-debugging-port port for the application. Once the browser is opened, the test can interact with the embedded web-content of the system under test.== Configuring the driver using the Service class ==
With the
serviceargument, one can setup and configure the driver. For example one can set the driver location and/port or specify the command line arguments. There are several browser specific attributes related to logging as well. For the various Service Class attributes refer to [https://www.selenium.dev/documentation/webdriver/drivers/service/|the Selenium documentation] . Currently theserviceargument only accepts Selenium service in the string format.=== Service string format ===
The string format allows for defining Selenium service attributes and their values in the Open Browser keyword. The attributes names are case and space sensitive and must match to the Selenium attributes names. Attributes are defined in a similar way as in Python: attribute name, equal sign, and attribute value. Example, port=1234. Multiple attributes must be separated by a semicolon. Example: executable_path=’/path/to/driver’;port=1234. Don’t have duplicate attributes, like service_args=[’–append-log’, ‘–readable-timestamp’]; service_args=[’–log-level=DEBUG’] as the second will override the first. Instead combine them as in service_args=[’–append-log’, ‘–readable-timestamp’, ‘–log-level=DEBUG’]
Arguments allow defining Python data types and arguments are evaluated by using Python. Strings must be quoted with single or double quotes, example “value” or ‘value’
= Timeouts, waits, and delays =
This section discusses different ways how to wait for elements to appear on web pages and to slow down execution speed otherwise. It also explains the time format that can be used when setting various timeouts, waits, and delays.
== Timeout ==
SeleniumLibrary contains various keywords that have an optional
timeoutargument that specifies how long these keywords should wait for certain events or actions. These keywords include, for example,Wait ...keywords and keywords related to alerts. Additionally Execute Async Javascript. Although it does not havetimeout, argument, uses a timeout to define how long asynchronous JavaScript can run.The default timeout these keywords use can be set globally either by using the Set Selenium Timeout keyword or with the
timeoutargument when importing the library. If no default timeout is set globally, the default is 5 seconds. If None is specified for the timeout argument in the keywords, the default is used. See time format below for supported timeout syntax.== Implicit wait ==
Implicit wait specifies the maximum time how long Selenium waits when searching for elements. It can be set by using the Set Selenium Implicit Wait keyword or with the
implicit_waitargument when importing the library. See [https://www.seleniumhq.org/docs/04_webdriver_advanced.jsp| Selenium documentation] for more information about this functionality.See time format below for supported syntax.
== Page load == Page load timeout is the amount of time to wait for page load to complete until a timeout exception is raised.
The default page load timeout can be set globally when importing the library with the
page_load_timeoutargument or by using the Set Selenium Page Load Timeout keyword.See time format below for supported timeout syntax.
Support for page load is new in SeleniumLibrary 6.1
== Selenium speed ==
Selenium execution speed can be slowed down globally by using Set Selenium speed keyword. This functionality is designed to be used for demonstrating or debugging purposes. Using it to make sure that elements appear on a page is not a good idea. The above-explained timeouts and waits should be used instead.
See time format below for supported syntax.
== Time format ==
All timeouts and waits can be given as numbers considered seconds (e.g.
0.5or42) or in Robot Framework’s time syntax (e.g.1.5 secondsor1 min 30 s). For more information about the time syntax see the [http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#time-format|Robot Framework User Guide].= Run-on-failure functionality =
SeleniumLibrary has a handy feature that it can automatically execute a keyword if any of its own keywords fails. By default, it uses the Capture Page Screenshot keyword, but this can be changed either by using the Register Keyword To Run On Failure keyword or with the
run_on_failureargument when importing the library. It is possible to use any keyword from any imported library or resource file.The run-on-failure functionality can be disabled by using a special value
NOTHINGor anything considered false (see Boolean arguments) such asNONE.= Boolean arguments =
Starting from 5.0 SeleniumLibrary relies on Robot Framework to perform the boolean conversion based on keyword arguments [https://docs.python.org/3/library/typing.html|type hint]. More details in Robot Framework [http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#supported-conversions|user guide]
Please note SeleniumLibrary 3 and 4 did have own custom methods to covert arguments to boolean values.
= EventFiringWebDriver =
The SeleniumLibrary offers support for [https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.event_firing_webdriver.html#module-selenium.webdriver.support.event_firing_webdriver|EventFiringWebDriver]. See the Selenium and SeleniumLibrary [https://github.com/robotframework/SeleniumLibrary/blob/master/docs/extending/extending.rst#EventFiringWebDriver|EventFiringWebDriver support] documentation for further details.
EventFiringWebDriver is new in SeleniumLibrary 4.0
= Thread support =
SeleniumLibrary is not thread-safe. This is mainly due because the underlying [https://github.com/SeleniumHQ/selenium/wiki/Frequently-Asked-Questions#q-is-webdriver-thread-safe| Selenium tool is not thread-safe] within one browser/driver instance. Because of the limitation in the Selenium side, the keywords or the API provided by the SeleniumLibrary is not thread-safe.
= Plugins =
SeleniumLibrary offers plugins as a way to modify and add library keywords and modify some of the internal functionality without creating a new library or hacking the source code. See [https://github.com/robotframework/SeleniumLibrary/blob/master/docs/extending/extending.rst#Plugins|plugin API] documentation for further details.
Plugin API is new SeleniumLibrary 4.0
= Language =
SeleniumLibrary offers the possibility to translate keyword names and documentation to new language. If language is defined, SeleniumLibrary will search from [https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#module-search-path | module search path] for Python packages starting with robotframework-seleniumlibrary-translation by using the [https://packaging.python.org/en/latest/guides/creating-and-discovering-plugins/ | Python pluging API]. The Library is using naming convention to find Python plugins.
The package must implement a single API call,
get_languagewithout any arguments. The method must return a dictionary containing two keys:languageandpath. The language key value defines which language the package contains. Also the value should match (case insensitive) the librarylanguageimport parameter. The path parameter value should be full path to the translation file.== Translation file ==
The file name or extension is not important, but data must be in [https://www.json.org/json-en.html | json] format. The keys of json are the methods names, not the keyword names, which implements keywords. Value of key is json object which contains two keys:
nameanddoc. Thenamekey contains the keyword translated name and doc contains translated documentation. Providing doc and name are optional, example translation json file can only provide translations to keyword names or only to documentation. But it is always recommended to provide translation to both name and doc. Special key__intro__is for class level documentation and__init__is for init level documentation. These special valuesnamecan not be translated, insteadnameshould be kept the same.== Generating template translation file ==
Template translation file, with English language can be created by running: rfselib translation /path/to/translation.json command. Command does not provide translations to other languages, it only provides easy way to create full list keywords and their documentation in correct format. It is also possible to add keywords from library plugins by providing –plugins arguments to command. Example: rfselib translation –plugins myplugin.SomePlugin /path/to/translation.json The generated json file contains sha256 key, which contains the sha256 sum of the library documentation. The sha256 sum is used by rfselib translation –compare /path/to/translation.json command, which compares the translation to the library and prints outs a table which tells if there are changes needed for the translation file.
Example project for translation can be found from [https://github.com/MarketSquare/robotframework-seleniumlibrary-translation-fi | robotframework-seleniumlibrary-translation-fi] repository.
= Auto closing browser =
By default, the browser instances created during a task execution are closed at the end of the task. This can be prevented with the
auto_closeparameter when importing the library.The value of the parameter needs to be set to
Falseor any object evaluated as false (see Boolean arguments).- AVAILABLE_OPTIONS = {'chrome': <class 'selenium.webdriver.chrome.options.Options'>, 'chromiumedge': <class 'selenium.webdriver.edge.options.Options'>, 'edge': <class 'selenium.webdriver.edge.options.Options'>, 'firefox': <class 'RPA.Browser.Selenium.FirefoxOptions'>, 'ie': <class 'selenium.webdriver.ie.options.Options'>, 'safari': <class 'selenium.webdriver.safari.options.Options'>}
- AVAILABLE_SERVICES = {'chrome': (<class 'selenium.webdriver.chrome.service.Service'>, 'chromedriver'), 'chromiumedge': (<class 'selenium.webdriver.edge.service.Service'>, 'msedgedriver'), 'edge': (<class 'selenium.webdriver.edge.service.Service'>, 'msedgedriver'), 'firefox': (<class 'selenium.webdriver.firefox.service.Service'>, 'geckodriver'), 'ie': (<class 'selenium.webdriver.ie.service.Service'>, 'IEDriverServer'), 'safari': (<class 'selenium.webdriver.safari.service.Service'>, 'safaridriver')}
- BROWSER_NAMES = {'chrome': 'chrome', 'chromiumedge': 'edge', 'edge': 'edge', 'ff': 'firefox', 'firefox': 'firefox', 'gc': 'chrome', 'googlechrome': 'chrome', 'headlesschrome': 'headless_chrome', 'headlessfirefox': 'headless_firefox', 'ie': 'ie', 'internetexplorer': 'ie', 'safari': 'safari'}
- CHROMIUM_BROWSERS = ['chrome', 'edge', 'chromiumedge', 'msedge', 'ie']
- ROBOT_LIBRARY_DOC_FORMAT = 'ROBOT'
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- ROBOT_LIBRARY_VERSION = '6.7.1'
- SUPPORTED_BROWSERS = {'chrome': 'Chrome', 'chromiumedge': 'ChromiumEdge', 'edge': 'Edge', 'firefox': 'Firefox', 'ie': 'Ie', 'safari': 'Safari'}
- add_library_components(library_components: List, translation: dict | None = None, translated_kw_names: list | None = None)
- attach_chrome_browser(port: int, alias: str | None = None) str | int
Attach to an existing instance of Chrome browser.
Requires that the browser was started with the command line option
--remote-debugging-port=<port>, where port is any 4-digit number not being used by other applications.Note. The first Chrome instance on the system needs to be started with this command line option or this won’t have an effect.
That port can then be used to connect using this keyword.
Example:
Attach Chrome Browser | port=9222 |
- clear_all_highlights()
Remove all highlighting made by
Highlight Elements.
- click_button_when_visible(locator: WebElement | ShadowRoot | str, modifier: str | None = None) None
Click button identified by
locator, once it becomes visible.locatorelement locatormodifierpress given keys while clicking the element, e.g. CTRLExample:
Click Button When Visible | //button[@class=”mybutton”] |
- click_element_if_visible(locator: WebElement | ShadowRoot | str) None
Click element if it is visible
locatorelement locatorExample:
Click Element If Visible | //button[@class=”mybutton”] |
- click_element_when_clickable(locator: WebElement | ShadowRoot | str, timeout: str | int | timedelta | None = None) None
Waits for and clicks an element until is fully ready to be clicked.
If a normal click doesn’t work, then JavaScript-oriented workarounds are tried as a fallback mechanism.
Parameter
locatortargets the element to be clicked. Parametertimeoutoptionally configures a custom duration to wait for the element to become clickable, until it gives up.Example:
Click Element When Clickable | example |
- click_element_when_visible(locator: WebElement | ShadowRoot | str, modifier: str | None = None, action_chain: bool = False) None
Click element identified by
locator, once it becomes visible.locatorelement locatormodifierpress given keys while clicking the element, e.g. CTRLaction_chainstore action in Selenium ActionChain queueExample:
Click Element When Visible | q |Click Element When Visible | id:button | CTRL+ALT |Click Element When Visible | action_chain=True |
- does_alert_contain(text: str | None = None, timeout: str | int | timedelta | None = None) bool
Does alert contain text.
textcheck if alert includes text, will raise ValueError is text does not existExample:
${res} | Does Alert Contain | alert message |
- does_alert_not_contain(text: str | None = None, timeout: str | int | timedelta | None = None) bool
Does alert not contain text.
textcheck that alert does not include text, will raise ValueError if text does existExample:
${res} | Does Alert Not Contain | unexpected message |
- does_element_contain(locator: WebElement | ShadowRoot | str, expected: str, ignore_case: bool = False) bool
Does element contain expected text
locatorelement locatorexpectedexpected element textignore_caseshould check be case insensitive, default FalseExample:
${res} | Does Element Contain | id:spec | specification complete | ignore_case=True |
- does_frame_contain(locator: WebElement | ShadowRoot | str, text: str) bool
Does frame contain expected text
locatorlocator of the frame to checktextdoes frame contain this textExample:
${res} | Does Frame Contain | id:myframe | secret |
- does_location_contain(expected: str) bool
Does current URL contain expected
expectedURL should contain thisExample:
Open Available Browser | https://robocorp.com |${res} | Does Location Contain | robocorp |
- does_page_contain(text: str) bool
Does page contain expected text
textpage should contain thisExample:
Open Available Browser | https://google.com |${res} | Does Page Contain | Gmail |
- does_page_contain_button(locator: WebElement | ShadowRoot | str) bool
Does page contain expected button
locatorelement locatorExample:
${res} | Does Page Contain Button | search-button |
- does_page_contain_checkbox(locator: WebElement | ShadowRoot | str) bool
Does page contain expected checkbox
locatorelement locatorExample:
${res} | Does Page Contain Checkbox | random-selection |
- does_page_contain_element(locator: WebElement | ShadowRoot | str, count: int | None = None) bool
Does page contain expected element
locatorelement locatorcounthow many times element is expected to appear on page by default one or moreExample:
${res} | Does Page Contain Element | textarea |${res} | Does Page Contain Element | button | count=4 |
- does_page_contain_image(locator: WebElement | ShadowRoot | str) bool
Does page contain expected image
locatorelement locatorExample:
Open Available Browser | https://google.com |${res} | Does Page Contain Image | Google |
- does_page_contain_link(locator: WebElement | ShadowRoot | str) bool
Does page contain expected link
locatorelement locatorExample:
${res} | Does Page Contain Link | id:submit |
- does_page_contain_list(locator: WebElement | ShadowRoot | str) bool
Does page contain expected list
locatorelement locatorExample:
${res} | Does Page Contain List | class:selections |
- does_page_contain_radio_button(locator: WebElement | ShadowRoot | str) bool
Does page contain expected radio button
locatorelement locatorExample:
${res} | Does Page Contain Radio Button | male |
- does_page_contain_textfield(locator: WebElement | ShadowRoot | str) bool
Does page contain expected textfield
locatorelement locatorExample:
${res} | Does Page Contain Textfield | id:address |
- does_table_cell_contain(locator: WebElement | ShadowRoot | str, row: int, column: int, expected: str) bool
Does table cell contain expected text
locatorelement locator for the tablerowrow index starting from 1 (beginning) or -1 (from the end)columncolumn index starting from 1 (beginning) or -1 (from the end)expectedexpected text in table rowExample:
${res} | Does Table Cell Contain | //table | 1 | 1 | Company |
- does_table_column_contain(locator: WebElement | ShadowRoot | str, column: int, expected: str) bool
Does table column contain expected text
locatorelement locator for the tablecolumncolumn index starting from 1 (beginning) or -1 (from the end)expectedexpected text in table columnExample:
${res} | Does Table Column Contain | //table | 1 | Nokia |
- does_table_contain(locator: WebElement | ShadowRoot | str, expected: str) bool
Does table contain expected text
locatorelement locatorexpectedexpected text in tableExample:
${res} | Does Table Contain | //table | February |
Does table footer contain expected text
locatorelement locator for the tableexpectedexpected text in table footerExample:
${res} | Does Table Footer Contain | //table | Sum |
- does_table_header_contain(locator: WebElement | ShadowRoot | str, expected: str) bool
Does table header contain expected text
locatorelement locator for the tableexpectedexpected text in table headerExample:
${res} | Does Table Header Contain | //table | Month |
- does_table_row_contain(locator: WebElement | ShadowRoot | str, row: int, expected: str) bool
Does table row contain expected text
locatorelement locator for the tablerowrow index starting from 1 (beginning) or -1 (from the end)expectedexpected text in table rowExample:
${res} | Does Table Row Contain | //table | 1 | Company |
- does_textarea_contain(locator: WebElement | ShadowRoot | str, expected: str) bool
Does textarea contain expected text
locatorelement locatorexpectedexpected text in textareaExample:
${res} | Does Textarea Contain | //textarea | sincerely |
- does_textfield_contain(locator: WebElement | ShadowRoot | str, expected: str) bool
Does textfield contain expected text
locatorelement locatorexpectedexpected text in textfieldExample:
${res} | Does Textfield Contain | id:lname | Last |
- property driver: WebDriver
Current active driver.
- Return type:
selenium.webdriver.remote.webdriver.WebDriver
- Raises:
SeleniumLibrary.errors.NoOpenBrowser – If browser is not open.
- execute_cdp(command, parameters)
Executes Chromium DevTools Protocol commands
Works only with Chromium-based browsers!
For more information, available commands and parameters, see: https://chromedevtools.github.io/devtools-protocol/
commandcommand to execute as stringparametersparameters for command as a dictionaryExample:
Open Chrome Browser | about:blank | headless=${True} |&{params} | Create Dictionary | userAgent=Chrome/83.0.4103.53 |Execute CDP | Network.setUserAgentOverride | ${params} |Go To | https://robocorp.com |
- failure_occurred()
Method that is executed when a SeleniumLibrary keyword fails.
By default, executes the registered run-on-failure keyword. Libraries extending SeleniumLibrary can overwrite this hook method if they want to provide custom functionality instead.
- find_element(locator: str, parent: WebElement | None = None) WebElement
Find element matching locator.
- Parameters:
locator (str or selenium.webdriver.remote.webelement.WebElement) – Locator to use when searching the element. See library documentation for the supported locator syntax.
parent (selenium.webdriver.remote.webelement.WebElement) – Optional parent WebElememt to search child elements from. By default, search starts from the root using WebDriver.
- Returns:
Found WebElement.
- Return type:
selenium.webdriver.remote.webelement.WebElement
- Raises:
SeleniumLibrary.errors.ElementNotFound – If element not found.
- find_elements(locator: str, parent: WebElement | None = None) List[WebElement]
Find all elements matching locator.
- Parameters:
locator (str or selenium.webdriver.remote.webelement.WebElement) – Locator to use when searching the element. See library documentation for the supported locator syntax.
parent (selenium.webdriver.remote.webelement.WebElement) – Optional parent WebElememt to search child elements from. By default, search starts from the root using WebDriver.
- Returns:
list of found WebElement or e,mpty if elements are not found.
- Return type:
list[selenium.webdriver.remote.webelement.WebElement]
- get_browser_capabilities() dict
Get dictionary of browser properties
Example:
${caps}= | Get Browser Capabilities |
- get_element_status(locator: WebElement | ShadowRoot | str) dict
Return dictionary containing element status of:
visible
enabled
disabled
focused
locatorelement locatorExample:
&{res} | Get Element Status | class:special |Log | ${res.visible} |Log | ${res.enabled} |Log | ${res.disabled} |Log | ${res.focused} |
- get_keyword_arguments(name)
- get_keyword_documentation(name: str) str
- get_keyword_names()
- get_keyword_source(keyword_name)
- get_keyword_tags(name: str) list
- get_keyword_types(name)
- get_testability_status() bool
Get SeleniumTestability plugin status
- get_webelement(locator: WebElement | ShadowRoot | str, parent: WebElement | ShadowRoot | None = None, shadow: bool = False) WebElement | ShadowRoot
Returns the first
Elementmatching the givenlocator.With the
parentparameter you can optionally specify a parent to start the search from. SetshadowtoTrueif you’re targeting and expecting a shadow root in return. Read more on the shadow root: https://developer.mozilla.org/en-US/docs/Web/API/ShadowRootSee the Locating elements section for details about the locator syntax.
- highlight_elements(locator: WebElement | ShadowRoot | str, width: str = '2px', style: str = 'dotted', color: str = 'blue')
Highlight all matching elements by locator.
Highlighting is done by adding a colored outline around the elements with CSS styling.
locatorelement locatorwidthhighlight outline widthstylehighlight outline stylecolorhighlight outline colorExample:
Highlight Elements | xpath://h2 |
- input_text_when_element_is_visible(locator: WebElement | ShadowRoot | str, text: str) None
Input text into locator after it has become visible.
locatorelement locatortextinsert text to locatorExample:
Input Text When Element Is Visible | //input[@id=”freetext”] | my feedback |
- is_alert_present(text: str | None = None, action: str = 'ACCEPT') bool
Is alert box present, which can be identified with text and action can also be done which by default is ACCEPT.
Other possible actions are DISMISS and LEAVE.
textcheck if alert text is matching to this, if None will check if alert is present at allactionpossible action if alert is present, default ACCEPTExample:
${res} | Is Alert Present | alert message |
- is_checkbox_selected(locator: WebElement | ShadowRoot | str) bool
Is checkbox selected
locatorelement locatorExample:
${res} | Is Checkbox Selected | id:taxes-paid |
- property is_chromium: bool
- is_element_attribute_equal_to(locator: WebElement | ShadowRoot | str, attribute: str, expected: str) bool
Is element attribute equal to expected value
locatorelement locatorattributeelement attribute to check forexpectedis attribute value equal to thisExample:
${res} | Is Element Attribute Equal To | h1 | id | main |
- is_element_disabled(locator: WebElement | ShadowRoot | str, missing_ok: bool = True) bool
Is element disabled
locatorelement locatormissing_okdefault True, set to False if keyword should Fail if element does not existExample:
${res} | Is Element Disabled | //input[@type=”submit”] |
- is_element_enabled(locator: WebElement | ShadowRoot | str, missing_ok: bool = True) bool
Is element enabled
locatorelement locatormissing_okdefault True, set to False if keyword should Fail if element does not existExample:
${res} | Is Element Enabled | input.field1 |
- is_element_focused(locator: WebElement | ShadowRoot | str, missing_ok: bool = True) bool
Is element focused
locatorelement locatormissing_okdefault True, set to False if keyword should Fail if element does not existExample:
${res} | Is Element Focused | //input[@id=”freetext”] |
- is_element_text(locator: WebElement | ShadowRoot | str, expected: str, ignore_case: bool = False) bool
Is element text expected
locatorelement locatorexpectedexpected element textignore_caseshould check be case insensitive, default FalseExample:
${res} | Is Element Text | id:name | john doe |${res} | Is Element Text | id:name | john doe | ignore_case=True |
- is_element_visible(locator: WebElement | ShadowRoot | str, missing_ok: bool = True) bool
Is element visible
locatorelement locatormissing_okdefault True, set to False if keyword should Fail if element does not existExample:
${res} | Is Element Visible | id:confirmation |
- is_list_selected(locator: WebElement | ShadowRoot | str) bool
Is any option selected in the
locatorelement locatorExample:
${res} | Is List Selected | id:cars |
- is_list_selection(locator: WebElement | ShadowRoot | str, *expected: str) bool
Is list selected with expected values
locatorelement locatorexpectedexpected selected optionsExample:
${res} | Is List Selection | id:cars | Ford |
- is_location(url: str) bool
Is current URL expected url
urlexpected current URLExample:
Open Available Browser | https://www.robocorp.com |${res} | Is Location | https://www.robocorp.com |
- is_radio_button_selected(group_name: str) bool
Is any radio button selected in the button group
group_nameradio button group nameExample:
${res} | Is Radio Button Selected | group_name=gender |
- is_radio_button_set_to(group_name: str, value: str) bool
Is radio button group set to expected value
group_nameradio button group namevalueexpected valueExample:
${res} | Is Radio Button Set To | group_name=gender | value=female |
- is_textarea_value(locator: WebElement | ShadowRoot | str, expected: str) bool
Is textarea matching expected value
locatorelement locatorexpectedexpected textarea valueExample:
${res} | Is Textarea Value | //textarea | Yours sincerely |
- is_textfield_value(locator: WebElement | ShadowRoot | str, expected: str) bool
Is textfield value expected
locatorelement locatorexpectedexpected textfield valueExample:
${res} | Is Textfield Value | id:lname | Lastname |
- is_title(title: str) bool
Is page title expected
titleexpected title valueExample:
${res} | Is Title | Webpage title text |
- property location: str
Return browser location.
- normalize_options(options: ArgOptions | str | Dict[str, str | List | Dict] | None, *, browser: str) ArgOptions
Normalize provided options to a <Browser>Options instance.
- open_available_browser(url: str | None = None, use_profile: bool = False, headless: bool | str = 'AUTO', maximized: bool = False, browser_selection: Any = 'AUTO', alias: str | None = None, profile_name: str | None = None, profile_path: str | None = None, preferences: dict | None = None, proxy: str = None, user_agent: str | None = None, download: Any = 'AUTO', options: ArgOptions | str | Dict[str, str | List | Dict] | None = None, port: int | None = None, sandbox: bool = False) str | int
Attempts to open a browser on the user’s device from a set of supported browsers. Automatically downloads a corresponding webdriver if none is already installed.
Currently supported browsers: Chrome, Firefox, Edge, ChromiumEdge, Safari, Ie
Optionally can be given a
urlas the first argument, to open the browser directly to the given page.Returns either a generated index or a custom
aliasfor the browser instance. The returned value can be used to refer to that specific browser instance in other keywords.If the browser should start in a maximized window, this can be enabled with the argument
maximized, but is disabled by default.For certain applications it might also be required to force a certain user-agent string for Selenium, which can be overridden with the
user_agentargument.WebDriver creation can be customized with
options. This accepts a class instance (e.g.ChromeOptions), a string like add_argument(”–incognito”);set_capability(“acceptInsecureCerts”, True) or even a simple dictionary like: {“arguments”: [”–incognito”], “capabilities”: {“acceptInsecureCerts”: True}}A custom
portcan be provided to start the browser webdriver without a randomly picked one. Make sure you provide every time a unique system-available local port if you plan to have multiple browsers being controlled in parallel.For incompatible web apps designed to work in Internet Explorer only, Edge can run in IE mode by simply setting ie in the
browser_selectionparam. Robot example: https://github.com/robocorp/example-ie-mode-edgeThe
sandboxargument can be used to enable the sandbox mode for the browser. By default browser is opened in –no-sandbox mode, but this started to cause issues on Chromium version 124. The –no-sandbox flag is set by default to preserve the older behavior.Example:
Open Available Browser | https://www.robocorp.com |${index}= | Open Available Browser | ${URL} | browser_selection=opera,firefox |Open Available Browser | ${URL} | headless=${True} | alias=HeadlessBrowser |Open Available Browser | ${URL} | options=add_argument(“user-data-dir=path/to/data”);add_argument(”–incognito”) |Open Available Browser | ${URL} | port=${8888} |== Browser order ==
The default order of supported browsers is based on the operating system and is as follows:
Platform | Default order |Windows| Chrome, Firefox, Edge |Linux| Chrome, Firefox, Edge |Darwin| Chrome, Firefox, Edge, Safari |The order can be overridden with a custom list by using the argument
browser_selection. The argument can be either a comma-separated string or a list object.Example:
Open Available Browser | ${URL} | browser_selection=ie |== Webdriver download ==
The library can (if requested) automatically download webdrivers for all the supported browsers. This can be controlled with the argument
download.If the value is
False, it will only attempt to start webdrivers found from the system PATH.If the value is
True, it will download a webdriver that matches the current browser.By default the argument has the value
AUTO, which means it first attempts to use webdrivers found in PATH and if that fails forces a webdriver download.== Opening process ==
Parse list of preferred browser order. If not given, use values from above table.
Loop through listed browsers:
Set the webdriver options for the browser.
Download webdriver (if requested).
Attempt to launch the webdriver and stop the loop if successful.
Return index/alias if webdriver was created, or raise an exception if no browsers were successfully opened.
== Headless mode ==
If required, the browser can also run headless, which means that it does not create a visible window. Generally a headless browser is slightly faster, but might not support all features a normal browser does.
One typical use-case for headless mode is in cloud containers, where there is no display available. It also prevents manual interaction with the browser, which can be either a benefit or a drawback depending on the context.
It can be explicitly enabled or disabled with the argument
headless. By default, it will be disabled, unless it detects that it is running in a Linux environment without a display, e.g. a container or if the RPA_HEADLESS_MODE env var is set to a number different than 0.== Chromium options ==
Some features are currently available only for Chromium-based browsers. This includes using an existing user profile. By default Selenium uses a new profile for each session, but it can use an existing one by enabling the
use_profileargument.If a custom profile is stored somewhere outside of the default location, the path to the profiles directory and the name of the profile can be controlled with
profile_pathandprofile_namerespectively. Keep in mind that theprofile_pathfor the Chrome browser for e.g. ends usually with “Chrome”, “User Data” or “google-chrome” (based on platform) and theprofile_nameis a directory relative toprofile_path, usually named “Profile 1”, “Profile 2” etc. (and not as your visible name in the Chrome browser). Similar behavior is observed with Edge as well.Example:
Open Available Browser | https://www.robocorp.com | use_profile=${True} |Open Available Browser | https://www.robocorp.com | use_profile=${True} | profile_name=Default |Open Available Browser | https://www.robocorp.com | use_profile=${True} | profile_name=Profile 2 |Open Available Browser | https://www.robocorp.com | use_profile=${True} | profile_name=Profile 1 | profile_path=path/to/custom/user_data_dir |Profile preferences can be further overridden with the
preferencesargument by giving a dictionary of key/value pairs.Chromium-based browsers can additionally connect through a
proxy, which should be given as either a local or remote address.
- open_chrome_browser(url: str, use_profile: bool = False, headless: bool | str = 'AUTO', maximized: bool = False, alias: str | None = None, profile_name: str | None = None, profile_path: str | None = None, preferences: dict | None = None, proxy: str | None = None, user_agent: str | None = None, sandbox: bool = False) str | int
Opens a Chrome browser.
See
Open Available Browserfor a full descriptions of the arguments.
- open_headless_chrome_browser(url: str) str | int
Opens the Chrome browser in headless mode.
urlURL to openExample:
${idx} = | Open Headless Chrome Browser | https://www.google.com |
- open_user_browser(url: str, tab=True) None
Opens an URL with te user’s default browser.
The browser opened with this keyword is not accessible with Selenium. To interact with the opened browser it is possible to use
RPA.DesktoporRPA.Windowslibrary keywords.The keyword Attach Chrome Browser can be used to access an already open browser with Selenium keywords.
Read more: https://robocorp.com/portal/tutorial/how-to-attach-to-running-chrome-browser
urlURL to opentabdefines is url is opened in a tab (defaults toTrue) orin new window (if set to
False)Example:
Open User Browser | https://www.google.com?q=rpa |Open User Browser | https://www.google.com?q=rpa | tab=${False} |
- print_to_pdf(output_path: str | None = None, params: dict | None = None) str
Print the current page to a PDF document using Chrome’s DevTools.
Attention: With some older browsers, this may work in headless mode only! For a list of supported parameters see: https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF Returns the output PDF file path.
Parameter
output_pathspecifies the file path for the generated PDF document. By default, it is saved to the output folder with the default name of out.pdf. Parameterparamsspecify parameters for the browser printing method. By default, it uses the following values: ``` {“landscape”: False, “displayHeaderFooter”: False, “printBackground”: True, “preferCSSPageSize”: True,
}
- register_driver(driver: WebDriver, alias: str)
Add’s a driver to the library WebDriverCache.
- Parameters:
driver (selenium.webdriver.remote.webdriver.WebDriver) – Instance of the Selenium WebDriver.
alias (str) – Alias given for this WebDriver instance.
- Returns:
The index of the WebDriver instance.
- Return type:
int
- run_keyword(name: str, args: tuple, kwargs: dict)
- screenshot(locator: WebElement | ShadowRoot | str | None = None, filename: str | None = '') str | None
Capture page and/or element screenshot.
locatorif defined, take element screenshot, if not takes page screenshotfilenamefilename for the screenshot, by default creates file screenshot-<timestamp>-(element|page).png if set to None then file is not saved at allExample:
Screenshot | locator=//img[@alt=”Google”] | filename=locator.png | # element screenshot, defined filename |Screenshot | filename=page.png | | # page screenshot, defined filename |Screenshot | filename=${NONE} | | # page screenshot, NO file will be created |Screenshot | | | # page screenshot, default filename |Screenshot | locator=//img[@alt=”Google”] | | # element screenshot, default filename |Screenshot | locator=//img[@alt=”Google”] | filename=${CURDIR}/subdir/loc.png | # element screenshot, create dirs if not existing |
- set_download_directory(directory: str | None = None, download_pdf: bool = True) None
Set a custom browser download directory.
This has to be called before opening the browser and it works with the following keywords:
Open Available BrowserOpen Chrome BrowserOpen Headless Chrome Browser
Supported browsers: Chrome, Edge, Firefox.
If the downloading doesn’t work (file is not found on disk), try using the browser in non-headless (headful) mode when opening it. (
headless=${False})Parameter
directorysets a path for downloads, defaults toNone, which means that this setting is removed and the default location will be used. Parameterdownload_pdfwill download a PDF file instead of previewing it within browser’s internal viewer when this is set toTrue. (enabled by default)Example:
Set Download Directory | ${OUTPUT_DIR} |Open Available Browser | https://cdn.robocorp.com/legal/Robocorp-EULA-v1.0.pdf |@{files} = | List Files In Directory | ${OUTPUT_DIR} |Log List | ${files} |
- set_element_attribute(locator: WebElement | ShadowRoot | str, attribute: str, value: str) None
Sets a
valuefor theattributein the elementlocator.See the Locating elements section for details about the locator syntax.
Example:
Set Element Attribute | css:h1 | class | active |
- wait_and_click_button(locator: WebElement | ShadowRoot | str, modifier: str | None = None) None
Click button identified by
locator, once it becomes visible.locatorelement locatormodifierpress given keys while clicking the element, e.g. CTRLExample:
Click Button When Visible | //button[@class=”mybutton”] |