SeleniumLibrary

Introduction

It uses the Selenium Remote Control tool internally to control a web browser. See http://selenium-rc.openqa.org/ for more information on Selenium tool.

SeleniumLibrary runs tests in a real browser instance. It should work in most modern browsers and can be used with both Python and Jython interpreters.

Before running the tests

Prior to running test cases using SeleniumLibrary, the Selenium Server must be started. This can be done using keyword Start Selenium Server or from the command line by using command: java -jar /path/to/selenium-server.jar. The Selenium Server is included in the SeleniumLibrary distribution and can be found under [PythonLibs]/site-packages/SeleniumLibrary/lib. Additionally, Open Browser keyword must be used in order to open browser in the desired location before any other keyword from the library may be used.

Locating elements

To do operations on elements, elements have to be identified. The most common way of doing this is by searching the values of key attributes of an element type. All keywords that operate on elements document the key attributes for that element type. If the given locator argument matches the value of any key attribute, the element is found.

Asterisk character may be used as a wildcard in locators, but it only works as the last character of the expression. In the middle of the locator it is interpreted as literal '*'.

It is also possible to give an arbitrary XPath or DOM expression as locator. In this case, the expression must be prefixed with either 'xpath=' or 'dom='.

All table related keywords (Table Should Contain, etc.) allow to identity a table either by the id of the table element, or by a css locator. Both of the following examples work. It's not possible to use an xpath or dom expression, since the table keywords use a css locator internally.

Table Examples:

Table Should Contain

tableID

$ 43,00

Table Should Contain

css=h2.someClass ~ table:last-child()

text

Handling page load events

Some keywords that may cause a page to load take an additional argument dont_wait that is used to determine whether a new page is expected to load or not. By default, a page load is expected to happen whenever a link or image is clicked, or a form submitted. If a page load does not happen (if the link only executes some JavaScript, for example), a non-empty value must be given for the dont_wait argument.

There are also some keywords that may cause a page to load but by default we expect them not to. For these cases, the keywords have an optional wait argument, and providing a non-empty value for it will cause the keyword to wait.

Importing

timeout is the default timeout used to wait for page load actions. It can be later set with Set Selenium Timeout

host and port are used to connect to Selenium Server. Browsers opened with this SeleniumLibrary instance will be attached to that server. Note that the Selenium Server must be running before Open Browser keyword can be used. Selenium Server can be started with keyword Start Selenium Server.

jar_path is the absolute path to the selenium-server.jar file to be used by the library. If set, a custom, modified version can be started instead of the default one distributed with the library.

run_on_failure specifies the name of a SeleniumLibrary keyword to execute when another SeleniumLibrary keyword fails. By default Capture Screenshot will be used to take a screenshot of the situation. Using any value that is not a keyword name will disable this feature altogether. See Register Keyword To Run On Failure keyword for more information about this functionality that was added in SeleniumLibrary 2.5.

Because there are many optional arguments, it is often a good idea to use the handy named-arguments syntax supported by Robot Framework 2.5 and later. This is demonstrated by the last example below.

Keywords

strategy_name is the name of the strategy; a prefix used when addressing an element.

function_definition is the JavaScript that will be called. It must return a DOM reference, an array with DOM references, or null.

Together with the modified selenium-server.jar it can provide a new method of locating elements on the page. For example, a jQuery strategy can be added to locate elements given jQuery selector syntax.

If text is a non-empty string, then it is also verified that the message of the alert equals to text.

Will fail if no alert is present. Note that when running tests with selenium, the alerts will not be visible in the browser. Nevertheless, following keywords will fail unless the alert is dismissed by this keyword or by Get Alert Message.

Call Selenium Api

method_name, *args

Calls a method in the Selenium remote control API directly.

This keyword can be used if some functionality provided by Selenium is not yet exposed as a keyword.

method_name is the name of the method to call in the Selenium API and args specify the arguments it expects.

The keyword first tries to find a method in Selenium's Python API provided by the selenium.py file. If no matching method is found, the keyword calls the Selenium Server's Remote Controller API directly via the do_command method in the Python API [1]. In both cases the keyword returns the return value of the call directly without any modifications or verifications.

filename argument specifies the name of the file to write the screenshot into. It works the same was as with Capture Screenshot.

css can be used to modify how the screenshot is taken. By default the bakground color is changed to avoid possible problems with background leaking when the page layout is somehow broken.

Selenium currently supports this keyword out-of-the-box only with Firefox browser. To make it work with IE, you can start the Selenium Server with -singleWindow option and use *ieproxy as the browser. Additionally, the browser independent Capture Screenshot keyword can be used instead.

This keyword was added in SeleniumLibrary 2.3.

Capture Screenshot

filename=None

Takes a screenshot of the entire screen and embeds it into the log.

If no filename is given, the screenshot is saved into file selenium-screenshot-<counter>.png under the directory where the Robot Framework log file is written into. The filename is also considered relative to the same directory, if it is not given in absolute format.

When running on a locked Windows machine, the resulting screenshots will be all black. A workaround is using the Capture Page Screenshot keyword instead.

There were some changes to this keyword in the 2.3 release:
- Possibility to take screenshots also when the Selenium Server is running on a remote machine was added.
- Support for absolute filename paths was added.
- Automatic creation of intermediate directories in the path where the screenshot is saved was removed. OperatingSystem.Create Directory can be used instead.

Checkbox Should Be Selected

locator

Verifies checkbox identified by locator is selected/checked.

Key attributes for checkboxes are id and name. See introduction for details about locating elements.

Checkbox Should Not Be Selected

locator

Verifies checkbox identified by locator is not selected/checked.

Key attributes for checkboxes are id and name. See introduction for details about locating elements.

This keyword is most often used to input files into upload forms. In normal usage the file specified with file_path must be available on the same host where the Selenium Server is running.

An alternative usage is specifying the file_path with an URL (starting with http:// or https://) in which case the file will be downloaded automatically. The limitations of this method are that it only works on Firefox and the file must be placed at the root level of a web server.

By default, this keyword chooses 'Ok' option from the dialog. If 'cancel' needs to be chosen, keyword Choose Cancel On Next Confirmation must be called before the action that causes the confirmation dialog to be shown.

Examples:

Click Button

Send

# Shows a confirmation dialog

${message}=

Confirm Action

# Chooses Ok

Should Be Equal

${message}

Are your sure?

Choose Cancel On Next Confirmation

Click Button

Send

# Shows a confirmation dialog

Confirm Action

# Chooses Cancel

Current Frame Contains

text, loglevel=INFO

Verifies that current page contains text.

If this keyword fails, it automatically logs the page source using the log level specified with the optional loglevel argument. Giving NONE as level disables logging.

The loglevel argument was added in SeleniumLibrary 2.3.1 and the special NONE argument value in SeleniumLibrary 2.5.

Current Frame Should Contain

text, loglevel=INFO

Verifies that current page contains text.

If this keyword fails, it automatically logs the page source using the log level specified with the optional loglevel argument. Giving NONE as level disables logging.

The loglevel argument was added in SeleniumLibrary 2.3.1 and the special NONE argument value in SeleniumLibrary 2.5.

options is the options for the cookie as a string. Currently supported options include path, domain and recurse. Format for options is path=/path/, domain=.foo.com, recurse=true. The order of options is irrelevant. Note that specifying a domain that is not a subset of the current domain will usually fail. Setting recurse=true will cause this keyword to search all sub-domains of current domain with all paths that are subset of current path. This can take a long time.

Drag And Drop

locator, movement

Drags element identified with locator by movement

`movement is a string in format "+70 -300" interpreted as pixels in relation to elements current position.

Element Should Be Visible

locator, message=

Verifies that the element identified by locator is visible.

Herein, visible means that the element is logically visible, not optically visible in the current browser viewport. For example, an element that carries display:none is not logically visible, so using this keyword on that element would fail.

message can be used to override the default error message.

Key attributes for arbitrary elements are id and name. See introduction for details about locating elements.

This keyword was added in SeleniumLibrary 2.5.

Element Should Contain

locator, expected, message=

Verifies element identified by locator contains text expected.

If you wish to assert an exact (not a substring) match on the text of the element, use Element Text Should Be.

message can be used to override the default error message.

Key attributes for arbitrary elements are id and name. See introduction for details about locating elements.

In contrast to Element Should Contain, this keyword does not try a substring match but an exact match on the element identified by locator.

message can be used to override the default error message.

Key attributes for arbitrary elements are id and name. See introduction for details about locating elements.

This keyword was added in SeleniumLibrary 2.5.

Execute Javascript

*code

Executes the given JavaScript code.

code may contain multiple statements and the return value of last statement is returned by this keyword.

code may be divided into multiple cells in the test data. In that case, the parts are catenated together without adding spaces.

If code is an absolute path to an existing file, the JavaScript to execute will be read from that file. Forward slashes work as a path separator on all operating systems. The functionality to read the code from a file was added in SeleniumLibrary 2.5.

Note that, by default, the code will be executed in the context of the Selenium object itself, so this will refer to the Selenium object. Use window to refer to the window of your application, e.g. window.document.getElementById('foo').

Example:

Execute JavaScript

window.my_js_function('arg1', 'arg2')

Execute JavaScript

${CURDIR}/js_to_execute.js

Focus

locator

Sets focus to element identified by locator.

This is useful for instance to direct native keystrokes to particular element using Press Key Native.

Frame Should Contain

locator, text, loglevel=INFO

Verifies frame identified by locator contains text.

See Page Should Contain for explanation about loglevel argument, that was added in SeleniumLibrary 2.5.

Key attributes for frames are id and name. See introduction for details about locating elements.

Frame Should Contain Text

locator, text, loglevel=INFO

Verifies frame identified by locator contains text.

See Page Should Contain for explanation about loglevel argument, that was added in SeleniumLibrary 2.5.

Key attributes for frames are id and name. See introduction for details about locating elements.

Get Alert Message

Returns the text of current JavaScript alert.

This keyword will fail if no alert is present. Note that when running tests with selenium, the alerts will not be visible in the browser. Nevertheless, following keywords will fail unless the alert is dismissed by this keyword or by Alert Should Be Present.

Get All Links

Returns a list containing ids of all links found in current page.

If a link has no id, an empty string will be in the list instead.

Get Cookie Value

name

Returns value of cookie found with name.

If no cookie is found with name, this keyword fails.

Get Cookies

Returns all cookies of the current page.

Get Element Attribute

attribute_locator

Return value of element attribute.

attribute_locator consists of element locator followed by an @ sign and attribute name, for example "element_id@class".

Get Horizontal Position

locator

Returns horizontal position of element identified by locator.

The position is returned in pixels off the left side of the page, as an integer. Fails if a matching element is not found.

Row and Column number start from 1. Header and footer rows are included in the count. This means that also cell content from header or footer rows can be obtained with this keyword. To understand how tables are identified, please take a look at the introduction.

Key attributes for images are id, src and alt. See introduction for details about locating elements.

Mouse Down On Link

locator

Simulates a mouse down event on a link.

Key attributes for links are id, name, href and link text. See introduction for details about locating elements.

Mouse Out

locator

Simulates moving mouse away from the element specified by locator.

Key attributes for arbitrary elements are id and name. See introduction for details about locating elements.

This keyword was added in SeleniumLibrary 2.5.

Mouse Over

locator

Simulates hovering mouse over the element specified by locator.

Key attributes for arbitrary elements are id and name. See introduction for details about locating elements.

This keyword was added in SeleniumLibrary 2.5.

Mouse Up

locator

Simulates releasing the left mouse button on the element specified by locator.

Key attributes for arbitrary elements are id and name. See introduction for details about locating elements.

This keyword was added in SeleniumLibrary 2.5.

Open Browser

url, browser=firefox, alias=None

Opens a new browser instance to given URL.

Possible already opened connections are cached.

Returns the index of this browser instance which can be used later to switch back to it. Index starts from 1 and is reset back to it when Close All Browsers keyword is used. See Switch Browser for example.

Optional alias is a alias for the browser instance and it can be used for switching between browsers similarly as the index. See Switch Browser for more details about that.

Possible values for browser are all the values supported by Selenium and some aliases that are defined for convenience. The table below lists the aliases for most common supported browsers.

firefox

FireFox

ff

FireFox

ie

Internet Explorer

internetexplorer

Internet Explorer

safari

Safari

googlechrome

Google Chrome

opera

Opera

Additionally, a string like *custom /path/to/browser-executable can be used to specify the browser directly. In this case, the path needs to point to an executable, not a script, otherwise the library may not be able to shut down the browser properly.

Sometimes this keyword does not trigger the correct JavaScript event on the clicked element. In those cases Press Key Native can be used as a workaround.

The selenium command key_press [1] that this keyword used exposes some erratic behavior [2], especially when used with the Internet Explorer. If you do not get the expected results, try Press Key Native instead.

Notice that this keyword is very fragile and, for example, using the keyboard or mouse while tests are running often causes problems. It can be beneficial to bring the window to the front again with executing JavaScript:

Execute Javascript

window.focus()

Focus

login_button

Press Key Native

10

and wait

Radio Button Should Be Set To

group_name, value

Verifies radio button group identified by group_name has its selection set to value.

Radio Button Should Not Be Selected

group_name

Verifies radio button group identified by group_name has no selection.

Register Keyword To Run On Failure

keyword_name

Sets the keyword to execute when a SeleniumLibrary keyword fails.

keyword_name is the name of a SeleniumLibrary keyword that will be executed if another SeleniumLibrary keyword fails. It is not possible to use a keyword that requires arguments. The name is case but not space sensitive. If the name does not match any keyword, this functionality is disabled and nothing extra will be done in case of a failure.

The initial keyword to use is set in importing, and the keyword that is used by default is Capture Screenshot. Taking a screenshot when something failed is a very useful feature, but notice that it can slow down the execution.

This keyword returns the name of the previously registered failure keyword. It can be used to restore the original value later.

# Disables run-on-failure functionality and stores the previous kw name in a variable.

Register Keyword To Run On Failure

${previous kw}

# Restore to the previous keyword.

The whole run-on-failure functionality is new in SeleniumLibrary 2.5. It only works when running tests on Python/Jython 2.4 or newer and it does not work on IronPython at all.

Select All From List

locator, wait=

Selects all values from multi-select list identified by id.

Key attributes for lists are id and name. See introduction for details about locating elements and about wait argument.

Select Checkbox

locator

Selects checkbox identified by locator.

Does nothing if checkbox is already selected. Key attributes for checkboxes are id and name. See introduction for details about locating elements.

Select Frame

locator

Sets frame identified by locator as current frame.

Key attributes for frames are id and name. See introduction for details about locating elements.

Select From List

locator, *values

Selects *values from list identified by locator

If more than one value is given for a single-selection list, the last value will be selected. If the target list is a multi-selection list, and *values is an empty list, all values of the list will be selected.

Key attributes for lists are id and name. See introduction for details about locating elements.

This keyword does not support waiting for possible page load automatically. If that is needed, keyword Wait Until Page Loaded can be used after this keyword.

Select Radio Button

group_name, value, wait=

Sets selection of radio button group identified by group_name to value.

The radio button to be selected is located by two arguments:
- group_name is used as the name of the radio input
- value is used for the value attribute or for the id attribute

The XPath used to locate the correct radio button then looks like this: //input[@type='radio' and @name='group_name' and (@value='value' or @id='value')]

If the window is found, all subsequent commands use that window, until this keyword is used again. If the window is not found, this keyword fails.

windowID may be either the title of the window or the name of the window in the JavaScript code that creates it. Name is second argument passed to JavaScript function window.open(). In case of multiple windows with same identifier are found, the first one is selected.

To select main window, the argument can be left empty, or name 'main' can be used.

Example:

Click Link

popup_link

don't wait

# opens new window

Select Window

popupName

Title Should Be

Popup Title

Select Window

# Chooses the main window again

Set Selenium Speed

seconds

Sets the delay that is waited after each Selenium command.

This is useful mainly in slowing down the test execution to be able to view the execution. seconds may be given in Robot Framework time format. Returns the previous speed value.

Example:

Set Selenium Speed

2 seconds

Set Selenium Timeout

seconds

Sets the timeout used by various keywords.

The keywords that expect a page load to happen will fail if the page does not load within the time specified with seconds. seconds may be given in Robot Framework time format and the default value is 5 seconds. Returns the previous timeout value.

Simulate

locator, event

Simulates event on element identified by locator.

This keyword is useful if element has OnEvent handler that needs to be explicitly invoked.

params can contain additional command line options given to the Selenium Server. This keyword uses some command line options automatically:

1) The port given in importing is added to params automatically using the -port option.

2) A custom Firefox profile that is included with the library and contains automation friendly settings is enabled via the -firefoxProfileTemplate option. You can override this profile with your own custom profile by using the same argument in params yourself. To use the default profile on your machine, use this argument with DEFAULT value. Using a custom Firefox profile automatically is a new feature in SeleniumLibrary 2.5. For more information see http://code.google.com/p/robotframework-seleniumlibrary/wiki/CustomFirefoxProfile

Above example expects that there was no other open browsers when opening the first one because it used index '1' when switching to it later. If you aren't sure about that you can store the index into a variable as below.

Verifies that a certain cell in a table contains the expected content.

Row and Column number start from 1. This keyword passes if the specified cell contains the given content. If you want to test that the cell content matches exactly, or that it e.g. starts with some text, use Get Table Cell keyword in combination with built-in keywords such as Should Be Equal or Should Start With.

To understand how tables are identified, please take a look at the introduction.

Table Column Should Contain

table_locator, col, expected_content, loglevel=INFO

Verifies that a specific column contains the expected_content.

The first leftmost column is column number 1. If the table contains cells that span multiple columns, those merged cells count as a single column. For example both tests below work, if in one row columns A and B are merged with colspan="2", and the logical third column contains "C".

Example:

Table Column Should Contain

tableId

3

C

Table Column Should Contain

tableId

2

C

To understand how tables are identified, please take a look at the introduction.