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
locator
that 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
id
andname
attributes, but some keywords support additional attributes or other values that make sense in their context. For example, Click Link supports thehref
attribute and the link text and addition to the normalid
andname
.Examples:
Click Element | example | # Match based onid
orname
. |Click Link | example | # Match also based on link text andhref
. |Click Button | example | # Match based onid
,name
orvalue
. |If a locator accidentally starts with a prefix recognized as explicit locator strategy or implicit XPath strategy, it is possible to use the explicit
default
prefix 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:value
orstrategy=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: foo
andid : foo
are 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 |name
attribute. |name:example
|identifier | Eitherid
orname
. |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
default
prefix 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:foo
or 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
,class
orcss
strategy liketag:h1
,class:example
orcss:h1.example
is 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:value
syntax is only supported by SeleniumLibrary 3.0 and newer.Using the
sizzle
strategy or its aliasjquery
requires that the system under test contains the jQuery library.Prior to SeleniumLibrary 3.0, table related keywords only supported
xpath
,css
andsizzle/jquery
strategies.data
strategy 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//div
is equivalent to using explicitxpath://div
and((//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
id
locator 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/.
= 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
timeout
argument 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
timeout
argument 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_wait
argument 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_timeout
argument 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.5
or42
) or in Robot Framework’s time syntax (e.g.1.5 seconds
or1 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_failure
argument 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
NOTHING
or 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
= 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_close
parameter when importing the library.The value of the parameter needs to be set to
False
or 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.3.0'
- SUPPORTED_BROWSERS = {'chrome': 'Chrome', 'chromiumedge': 'ChromiumEdge', 'edge': 'Edge', 'firefox': 'Firefox', 'ie': 'Ie', 'safari': 'Safari'}
- add_library_components(library_components: List, translation: Optional[dict] = None, translated_kw_names: Optional[list] = None)
- attach_chrome_browser(port: int, alias: Optional[str] = None) Union[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: Union[WebElement, ShadowRoot, str], modifier: Optional[str] = None) None
Click button identified by
locator
, once it becomes visible.locator
element locatormodifier
press given keys while clicking the element, e.g. CTRLExample:
Click Button When Visible | //button[@class=”mybutton”] |
- click_element_if_visible(locator: Union[WebElement, ShadowRoot, str]) None
Click element if it is visible
locator
element locatorExample:
Click Element If Visible | //button[@class=”mybutton”] |
- click_element_when_clickable(locator: Union[WebElement, ShadowRoot, str], timeout: Optional[Union[str, int, timedelta]] = 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
locator
targets the element to be clicked. Parametertimeout
optionally 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: Union[WebElement, ShadowRoot, str], modifier: Optional[str] = None, action_chain: bool = False) None
Click element identified by
locator
, once it becomes visible.locator
element locatormodifier
press given keys while clicking the element, e.g. CTRLaction_chain
store 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: Optional[str] = None, timeout: Optional[Union[str, int, timedelta]] = None) bool
Does alert contain text.
text
check if alert includes text, will raise ValueError is text does not existExample:
${res} | Does Alert Contain | alert message |
- does_alert_not_contain(text: Optional[str] = None, timeout: Optional[Union[str, int, timedelta]] = None) bool
Does alert not contain text.
text
check that alert does not include text, will raise ValueError if text does existExample:
${res} | Does Alert Not Contain | unexpected message |
- does_element_contain(locator: Union[WebElement, ShadowRoot, str], expected: str, ignore_case: bool = False) bool
Does element contain expected text
locator
element locatorexpected
expected element textignore_case
should check be case insensitive, default FalseExample:
${res} | Does Element Contain | id:spec | specification complete | ignore_case=True |
- does_frame_contain(locator: Union[WebElement, ShadowRoot, str], text: str) bool
Does frame contain expected text
locator
locator of the frame to checktext
does frame contain this textExample:
${res} | Does Frame Contain | id:myframe | secret |
- does_location_contain(expected: str) bool
Does current URL contain expected
expected
URL 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
text
page should contain thisExample:
Open Available Browser | https://google.com |${res} | Does Page Contain | Gmail |
- does_page_contain_button(locator: Union[WebElement, ShadowRoot, str]) bool
Does page contain expected button
locator
element locatorExample:
${res} | Does Page Contain Button | search-button |
- does_page_contain_checkbox(locator: Union[WebElement, ShadowRoot, str]) bool
Does page contain expected checkbox
locator
element locatorExample:
${res} | Does Page Contain Checkbox | random-selection |
- does_page_contain_element(locator: Union[WebElement, ShadowRoot, str], count: Optional[int] = None) bool
Does page contain expected element
locator
element locatorcount
how 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: Union[WebElement, ShadowRoot, str]) bool
Does page contain expected image
locator
element locatorExample:
Open Available Browser | https://google.com |${res} | Does Page Contain Image | Google |
- does_page_contain_link(locator: Union[WebElement, ShadowRoot, str]) bool
Does page contain expected link
locator
element locatorExample:
${res} | Does Page Contain Link | id:submit |
- does_page_contain_list(locator: Union[WebElement, ShadowRoot, str]) bool
Does page contain expected list
locator
element locatorExample:
${res} | Does Page Contain List | class:selections |
- does_page_contain_radio_button(locator: Union[WebElement, ShadowRoot, str]) bool
Does page contain expected radio button
locator
element locatorExample:
${res} | Does Page Contain Radio Button | male |
- does_page_contain_textfield(locator: Union[WebElement, ShadowRoot, str]) bool
Does page contain expected textfield
locator
element locatorExample:
${res} | Does Page Contain Textfield | id:address |
- does_table_cell_contain(locator: Union[WebElement, ShadowRoot, str], row: int, column: int, expected: str) bool
Does table cell contain expected text
locator
element locator for the tablerow
row index starting from 1 (beginning) or -1 (from the end)column
column index starting from 1 (beginning) or -1 (from the end)expected
expected text in table rowExample:
${res} | Does Table Cell Contain | //table | 1 | 1 | Company |
- does_table_column_contain(locator: Union[WebElement, ShadowRoot, str], column: int, expected: str) bool
Does table column contain expected text
locator
element locator for the tablecolumn
column index starting from 1 (beginning) or -1 (from the end)expected
expected text in table columnExample:
${res} | Does Table Column Contain | //table | 1 | Nokia |
- does_table_contain(locator: Union[WebElement, ShadowRoot, str], expected: str) bool
Does table contain expected text
locator
element locatorexpected
expected text in tableExample:
${res} | Does Table Contain | //table | February |
Does table footer contain expected text
locator
element locator for the tableexpected
expected text in table footerExample:
${res} | Does Table Footer Contain | //table | Sum |
- does_table_header_contain(locator: Union[WebElement, ShadowRoot, str], expected: str) bool
Does table header contain expected text
locator
element locator for the tableexpected
expected text in table headerExample:
${res} | Does Table Header Contain | //table | Month |
- does_table_row_contain(locator: Union[WebElement, ShadowRoot, str], row: int, expected: str) bool
Does table row contain expected text
locator
element locator for the tablerow
row index starting from 1 (beginning) or -1 (from the end)expected
expected text in table rowExample:
${res} | Does Table Row Contain | //table | 1 | Company |
- does_textarea_contain(locator: Union[WebElement, ShadowRoot, str], expected: str) bool
Does textarea contain expected text
locator
element locatorexpected
expected text in textareaExample:
${res} | Does Textarea Contain | //textarea | sincerely |
- does_textfield_contain(locator: Union[WebElement, ShadowRoot, str], expected: str) bool
Does textfield contain expected text
locator
element locatorexpected
expected 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/
command
command to execute as stringparameters
parameters 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: Optional[WebElement] = 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: Optional[WebElement] = 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: Union[WebElement, ShadowRoot, str]) dict
Return dictionary containing element status of:
visible
enabled
disabled
focused
locator
element 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: Union[WebElement, ShadowRoot, str], parent: Optional[Union[WebElement, ShadowRoot]] = None, shadow: bool = False) Union[WebElement, ShadowRoot]
Returns the first
Element
matching the givenlocator
.With the
parent
parameter you can optionally specify a parent to start the search from. Setshadow
toTrue
if 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: Union[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.
locator
element locatorwidth
highlight outline widthstyle
highlight outline stylecolor
highlight outline colorExample:
Highlight Elements | xpath://h2 |
- input_text_when_element_is_visible(locator: Union[WebElement, ShadowRoot, str], text: str) None
Input text into locator after it has become visible.
locator
element locatortext
insert text to locatorExample:
Input Text When Element Is Visible | //input[@id=”freetext”] | my feedback |
- is_alert_present(text: Optional[str] = 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.
text
check if alert text is matching to this, if None will check if alert is present at allaction
possible action if alert is present, default ACCEPTExample:
${res} | Is Alert Present | alert message |
- is_checkbox_selected(locator: Union[WebElement, ShadowRoot, str]) bool
Is checkbox selected
locator
element locatorExample:
${res} | Is Checkbox Selected | id:taxes-paid |
- property is_chromium: bool
- is_element_attribute_equal_to(locator: Union[WebElement, ShadowRoot, str], attribute: str, expected: str) bool
Is element attribute equal to expected value
locator
element locatorattribute
element attribute to check forexpected
is attribute value equal to thisExample:
${res} | Is Element Attribute Equal To | h1 | id | main |
- is_element_disabled(locator: Union[WebElement, ShadowRoot, str], missing_ok: bool = True) bool
Is element disabled
locator
element locatormissing_ok
default True, set to False if keyword should Fail if element does not existExample:
${res} | Is Element Disabled | //input[@type=”submit”] |
- is_element_enabled(locator: Union[WebElement, ShadowRoot, str], missing_ok: bool = True) bool
Is element enabled
locator
element locatormissing_ok
default True, set to False if keyword should Fail if element does not existExample:
${res} | Is Element Enabled | input.field1 |
- is_element_focused(locator: Union[WebElement, ShadowRoot, str], missing_ok: bool = True) bool
Is element focused
locator
element locatormissing_ok
default True, set to False if keyword should Fail if element does not existExample:
${res} | Is Element Focused | //input[@id=”freetext”] |
- is_element_text(locator: Union[WebElement, ShadowRoot, str], expected: str, ignore_case: bool = False) bool
Is element text expected
locator
element locatorexpected
expected element textignore_case
should 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: Union[WebElement, ShadowRoot, str], missing_ok: bool = True) bool
Is element visible
locator
element locatormissing_ok
default True, set to False if keyword should Fail if element does not existExample:
${res} | Is Element Visible | id:confirmation |
- is_list_selected(locator: Union[WebElement, ShadowRoot, str]) bool
Is any option selected in the
locator
element locatorExample:
${res} | Is List Selected | id:cars |
- is_list_selection(locator: Union[WebElement, ShadowRoot, str], *expected: str) bool
Is list selected with expected values
locator
element locatorexpected
expected selected optionsExample:
${res} | Is List Selection | id:cars | Ford |
- is_location(url: str) bool
Is current URL expected url
url
expected 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_name
radio 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_name
radio button group namevalue
expected valueExample:
${res} | Is Radio Button Set To | group_name=gender | value=female |
- is_textarea_value(locator: Union[WebElement, ShadowRoot, str], expected: str) bool
Is textarea matching expected value
locator
element locatorexpected
expected textarea valueExample:
${res} | Is Textarea Value | //textarea | Yours sincerely |
- is_textfield_value(locator: Union[WebElement, ShadowRoot, str], expected: str) bool
Is textfield value expected
locator
element locatorexpected
expected textfield valueExample:
${res} | Is Textfield Value | id:lname | Lastname |
- is_title(title: str) bool
Is page title expected
title
expected title valueExample:
${res} | Is Title | Webpage title text |
- property location: str
Return browser location.
- normalize_options(options: Optional[Union[ArgOptions, str, Dict[str, Union[str, List, Dict]]]], *, browser: str) ArgOptions
Normalize provided options to a <Browser>Options instance.
- open_available_browser(url: Optional[str] = None, use_profile: bool = False, headless: Union[bool, str] = 'AUTO', maximized: bool = False, browser_selection: Any = 'AUTO', alias: Optional[str] = None, profile_name: Optional[str] = None, profile_path: Optional[str] = None, preferences: Optional[dict] = None, proxy: str = None, user_agent: Optional[str] = None, download: Any = 'AUTO', options: Optional[Union[ArgOptions, str, Dict[str, Union[str, List, Dict]]]] = None, port: Optional[int] = None, sandbox: bool = False) Union[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
url
as the first argument, to open the browser directly to the given page.Returns either a generated index or a custom
alias
for 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_agent
argument.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
port
can 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_selection
param. Robot example: https://github.com/robocorp/example-ie-mode-edgeThe
sandbox
argument 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_profile
argument.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_path
andprofile_name
respectively. Keep in mind that theprofile_path
for the Chrome browser for e.g. ends usually with “Chrome”, “User Data” or “google-chrome” (based on platform) and theprofile_name
is 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
preferences
argument 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: Union[bool, str] = 'AUTO', maximized: bool = False, alias: Optional[str] = None, profile_name: Optional[str] = None, profile_path: Optional[str] = None, preferences: Optional[dict] = None, proxy: Optional[str] = None, user_agent: Optional[str] = None, sandbox: bool = False) Union[str, int]
Opens a Chrome browser.
See
Open Available Browser
for a full descriptions of the arguments.
- open_headless_chrome_browser(url: str) Union[str, int]
Opens the Chrome browser in headless mode.
url
URL 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.Desktop
orRPA.Windows
library keywords.The keyword Attach Chrome Browser can be used to access an already open browser with Selenium keywords.
Read more: https://robocorp.com/docs/development-guide/browser/how-to-attach-to-running-chrome-browser
url
URL to opentab
defines 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: Optional[str] = None, params: Optional[dict] = 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_path
specifies the file path for the generated PDF document. By default, it is saved to the output folder with the default name of out.pdf. Parameterparams
specify 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: Optional[Union[WebElement, ShadowRoot, str]] = None, filename: Optional[str] = '') Optional[str]
Capture page and/or element screenshot.
locator
if defined, take element screenshot, if not takes page screenshotfilename
filename 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: Optional[str] = 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 Browser
Open Chrome Browser
Open 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
directory
sets a path for downloads, defaults toNone
, which means that this setting is removed and the default location will be used. Parameterdownload_pdf
will 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: Union[WebElement, ShadowRoot, str], attribute: str, value: str) None
Sets a
value
for theattribute
in 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: Union[WebElement, ShadowRoot, str], modifier: Optional[str] = None) None
Click button identified by
locator
, once it becomes visible.locator
element locatormodifier
press given keys while clicking the element, e.g. CTRLExample:
Click Button When Visible | //button[@class=”mybutton”] |