API Reference

Marionette

class marionette_driver.marionette.Marionette(host='localhost', port=2828, app=None, bin=None, baseurl=None, socket_timeout=None, startup_timeout=None, **instance_args)

Represents a Marionette connection to a browser or device.

absolute_url(relative_url)

Returns an absolute url for files served from Marionette’s www directory.

Parameters:relative_url – The url of a static file, relative to Marionette’s www directory.

Adds a cookie to your current session.

Parameters:cookie – A dictionary object, with required keys - “name” and “value”; optional keys - “path”, “domain”, “secure”, “expiry”.

Usage example:

driver.add_cookie({"name": "foo", "value": "bar"})
driver.add_cookie({"name": "foo", "value": "bar", "path": "/"})
driver.add_cookie({"name": "foo", "value": "bar", "path": "/",
                   "secure": True})
check_for_crash()

Check if the process crashed.

Returns:True, if a crash happened since the method has been called the last time.
chrome_window_handles

Get a list of currently open chrome windows.

Each window handle is assigned by the server, and the list of strings returned does not have a guaranteed ordering.

Returns:Unordered list of unique chrome window handles as strings
clear_pref(pref)

Clear the user-defined value from the specified preference.

Parameters:pref – Name of the preference.
close()

Close the current window, ending the session if it’s the last window currently open.

Returns:Unordered list of remaining unique window handles as strings
close_chrome_window()

Close the currently selected chrome window, ending the session if it’s the last window open.

Returns:Unordered list of remaining unique chrome window handles as strings
current_chrome_window_handle

Get the current chrome window’s handle. Corresponds to a chrome window that may itself contain tabs identified by window_handles.

Returns an opaque server-assigned identifier to this window that uniquely identifies it within this Marionette instance. This can be used to switch to this window at a later point.

Returns:unique window handle
Return type:string
current_window_handle

Get the current window’s handle.

Returns an opaque server-assigned identifier to this window that uniquely identifies it within this Marionette instance. This can be used to switch to this window at a later point.

Returns:unique window handle
Return type:string
delete_all_cookies()

Delete all cookies in the scope of the current session.

Usage example:

driver.delete_all_cookies()

Delete a cookie by its name.

Parameters:name – Name of cookie to delete.

Usage example:

driver.delete_cookie("foo")
delete_session(send_request=True, reset_session_id=False)

Close the current session and disconnect from the server.

Parameters:
  • send_request – Optional, if True a request to close the session on the server side will be sent. Use False in case of eg. in_app restart() or quit(), which trigger a deletion themselves. Defaults to True.
  • reset_session_id – Optional, if True the current session id will be reset, which will require an explicit call to start_session() before the test can continue. Defaults to False.
enforce_gecko_prefs(*args, **kwargs)

Checks if the running instance has the given prefs. If not, it will kill the currently running instance, and spawn a new instance with the requested preferences.

Parameters:prefs – A dictionary whose keys are preference names.
execute_async_script(script, script_args=(), new_sandbox=True, sandbox='default', script_timeout=None, debug_script=False)

Executes an asynchronous JavaScript script, and returns the result (or None if the script does return a value).

The script is executed in the context set by the most recent set_context() call, or to the CONTEXT_CONTENT context if set_context() has not been called.

Parameters:
  • script – A string containing the JavaScript to execute.
  • script_args – An interable of arguments to pass to the script.
  • sandbox – A tag referring to the sandbox you wish to use; if you specify a new tag, a new sandbox will be created. If you use the special tag system, the sandbox will be created using the system principal which has elevated privileges.
  • new_sandbox – If False, preserve global variables from the last execute_*script call. This is True by default, in which case no globals are preserved.
  • debug_script – Capture javascript exceptions when in CONTEXT_CHROME context.

Usage example:

marionette.timeout.script = 10
result = self.marionette.execute_async_script('''
  // this script waits 5 seconds, and then returns the number 1
  setTimeout(function() {
    marionetteScriptFinished(1);
  }, 5000);
''')
assert result == 1
execute_script(script, script_args=(), new_sandbox=True, sandbox='default', script_timeout=None)

Executes a synchronous JavaScript script, and returns the result (or None if the script does return a value).

The script is executed in the context set by the most recent set_context() call, or to the CONTEXT_CONTENT context if set_context() has not been called.

Parameters:
  • script – A string containing the JavaScript to execute.
  • script_args – An interable of arguments to pass to the script.
  • sandbox – A tag referring to the sandbox you wish to use; if you specify a new tag, a new sandbox will be created. If you use the special tag system, the sandbox will be created using the system principal which has elevated privileges.
  • new_sandbox – If False, preserve global variables from the last execute_*script call. This is True by default, in which case no globals are preserved.

Simple usage example:

result = marionette.execute_script("return 1;")
assert result == 1

You can use the script_args parameter to pass arguments to the script:

result = marionette.execute_script("return arguments[0] + arguments[1];",
                                   script_args=(2, 3,))
assert result == 5
some_element = marionette.find_element(By.ID, "someElement")
sid = marionette.execute_script("return arguments[0].id;", script_args=(some_element,))
assert some_element.get_attribute("id") == sid

Scripts wishing to access non-standard properties of the window object must use window.wrappedJSObject:

result = marionette.execute_script('''
  window.wrappedJSObject.test1 = "foo";
  window.wrappedJSObject.test2 = "bar";
  return window.wrappedJSObject.test1 + window.wrappedJSObject.test2;
  ''')
assert result == "foobar"

Global variables set by individual scripts do not persist between script calls by default. If you wish to persist data between script calls, you can set new_sandbox to False on your next call, and add any new variables to a new ‘global’ object like this:

marionette.execute_script("global.test1 = 'foo';")
result = self.marionette.execute_script("return global.test1;", new_sandbox=False)
assert result == "foo"
find_element(method, target, id=None)

Returns an HTMLElement instance that matches the specified method and target in the current context.

An HTMLElement instance may be used to call other methods on the element, such as click(). If no element is immediately found, the attempt to locate an element will be repeated for up to the amount of time set by marionette_driver.timeout.Timeouts.implicit. If multiple elements match the given criteria, only the first is returned. If no element matches, a NoSuchElementException will be raised.

Parameters:
  • method – The method to use to locate the element; one of: “id”, “name”, “class name”, “tag name”, “css selector”, “link text”, “partial link text”, “xpath”, “anon” and “anon attribute”. Note that the “name”, “link text” and “partial link test” methods are not supported in the chrome DOM.
  • target – The target of the search. For example, if method = “tag”, target might equal “div”. If method = “id”, target would be an element id.
  • id – If specified, search for elements only inside the element with the specified id.
find_elements(method, target, id=None)

Returns a list of all HTMLElement instances that match the specified method and target in the current context.

An HTMLElement instance may be used to call other methods on the element, such as click(). If no element is immediately found, the attempt to locate an element will be repeated for up to the amount of time set by marionette_driver.timeout.Timeouts.implicit.

Parameters:
  • method – The method to use to locate the elements; one of: “id”, “name”, “class name”, “tag name”, “css selector”, “link text”, “partial link text”, “xpath”, “anon” and “anon attribute”. Note that the “name”, “link text” and “partial link test” methods are not supported in the chrome DOM.
  • target – The target of the search. For example, if method = “tag”, target might equal “div”. If method = “id”, target would be an element id.
  • id – If specified, search for elements only inside the element with the specified id.
fullscreen()

Synchronously sets the user agent window to full screen as if the user had done “View > Enter Full Screen”, or restores it if it is already in full screen.

Returns:Window rect.
get_active_frame()

Returns an HTMLElement representing the frame Marionette is currently acting on.

Get a single cookie by name. Returns the cookie if found, None if not.

Parameters:name – Name of cookie to get.
get_cookies()

Get all the cookies for the current domain.

This is the equivalent of calling document.cookie and parsing the result.

Returns:A list of cookies for the current domain.
get_pref(pref, default_branch=False, value_type='nsISupportsString')

Get the value of the specified preference.

Parameters:
  • pref – Name of the preference.
  • default_branch – Optional, if True the preference value will be read from the default branch. Otherwise the user-defined value if set is returned. Defaults to False.
  • value_type – Optional, XPCOM interface of the pref’s complex value. Defaults to nsISupportsString. Other possible values are: nsIFile, and nsIPrefLocalizedString.

Usage example:

marionette.get_pref("browser.tabs.warnOnClose")
get_url()

Get a string representing the current URL.

On Desktop this returns a string representation of the URL of the current top level browsing context. This is equivalent to document.location.href.

When in the context of the chrome, this returns the canonical URL of the current resource.

Returns:string representation of URL
get_window_position()

Get the current window’s position.

Returns:a dictionary with x and y
get_window_type()

Gets the windowtype attribute of the window Marionette is currently acting on.

This command only makes sense in a chrome context. You might use this method to distinguish a browser window from an editor window.

go_back()

Causes the browser to perform a back navigation.

go_forward()

Causes the browser to perform a forward navigation.

maximize_window()

Resize the browser window currently receiving commands. The action should be equivalent to the user pressing the maximize button in the OS window.

Note that this command is not available on Fennec. It may also not be available in certain window managers.

Returns:Window rect.
minimize_window()

Iconify the browser window currently receiving commands. The action should be equivalent to the user pressing the minimize button in the OS window.

Note that this command is not available on Fennec. It may also not be available in certain window managers.

:returns Window rect.

navigate(url)

Navigate to given url.

Navigates the current top-level browsing context’s content frame to the given URL and waits for the document to load or the session’s page timeout duration to elapse before returning.

The command will return with a failure if there is an error loading the document or the URL is blocked. This can occur if it fails to reach the host, the URL is malformed, the page is restricted (about:* pages), or if there is a certificate issue to name some examples.

The document is considered successfully loaded when the DOMContentLoaded event on the frame element associated with the window triggers and document.readyState is “complete”.

In chrome context it will change the current window‘s location to the supplied URL and wait until document.readyState equals “complete” or the page timeout duration has elapsed.

Parameters:url – The URL to navigate to.
orientation

Get the current browser orientation.

Will return one of the valid primary orientation values portrait-primary, landscape-primary, portrait-secondary, or landscape-secondary.

page_source

A string representation of the DOM.

quit(*args, **kwargs)

Terminate the currently running instance.

This command will delete the active marionette session. It also allows manipulation of eg. the profile data while the application is not running. To start the application again, start_session() has to be called.

Parameters:
  • clean – If False the same profile will be used after the next start of the application. Note that the in app initiated restart always maintains the same profile.
  • in_app – If True, marionette will cause a quit from within the browser. Otherwise the browser will be quit immediately by killing the process.
  • callback – If provided and in_app is True, the callback will be used to trigger the shutdown.
raise_for_port(timeout=None)

Raise socket.timeout if no connection can be established.

Parameters:timeout – Timeout in seconds for the server to be ready.
refresh()

Causes the browser to perform to refresh the current page.

restart(*args, **kwargs)

This will terminate the currently running instance, and spawn a new instance with the same profile and then reuse the session id when creating a session again.

Parameters:
  • clean – If False the same profile will be used after the restart. Note that the in app initiated restart always maintains the same profile.
  • in_app – If True, marionette will cause a restart from within the browser. Otherwise the browser will be restarted immediately by killing the process.
  • callback – If provided and in_app is True, the callback will be used to trigger the restart.
screenshot(element=None, highlights=None, format='base64', full=True, scroll=True)

Takes a screenshot of a web element or the current frame.

The screen capture is returned as a lossless PNG image encoded as a base 64 string by default. If the element argument is defined the capture area will be limited to the bounding box of that element. Otherwise, the capture area will be the bounding box of the current frame.

Parameters:
  • element – The element to take a screenshot of. If None, will take a screenshot of the current frame.
  • highlights – A list of HTMLElement objects to draw a red box around in the returned screenshot.
  • format – if “base64” (the default), returns the screenshot as a base64-string. If “binary”, the data is decoded and returned as raw binary. If “hash”, the data is hashed using the SHA-256 algorithm and the result is returned as a hex digest.
  • full – If True (the default), the capture area will be the complete frame. Else only the viewport is captured. Only applies when element is None.
  • scroll – When element is provided, scroll to it before taking the screenshot (default). Otherwise, avoid scrolling element into view.
session_capabilities

A JSON dictionary representing the capabilities of the current session.

set_context(context)

Sets the context that Marionette commands are running in.

Parameters:context – Context, may be one of the class properties CONTEXT_CHROME or CONTEXT_CONTENT.

Usage example:

marionette.set_context(marionette.CONTEXT_CHROME)
set_orientation(orientation)

Set the current browser orientation.

The supplied orientation should be given as one of the valid orientation values. If the orientation is unknown, an error will be raised.

Valid orientations are “portrait” and “landscape”, which fall back to “portrait-primary” and “landscape-primary” respectively, and “portrait-secondary” as well as “landscape-secondary”.

Parameters:orientation – The orientation to lock the screen in.
set_page_load_timeout(timeout)

Sets a timeout for loading pages.

A page load timeout specifies the amount of time the Marionette instance should wait for a page load operation to complete. A TimeoutException is returned if this limit is exceeded.

Parameters:timeout – Timeout in milliseconds.

Note

set_page_load_timeout is deprecated, please use timeout.page_load setter.

set_pref(pref, value, default_branch=False)

Set the value of the specified preference.

Parameters:
  • pref – Name of the preference.
  • value – The value to set the preference to. If the value is None, reset the preference to its default value. If no default value exists, the preference will cease to exist.
  • default_branch – Optional, if True the preference value will be written to the default branch, and will remain until the application gets restarted. Otherwise a user-defined value is set. Defaults to False.

Usage example:

marionette.set_pref("browser.tabs.warnOnClose", True)
set_prefs(prefs, default_branch=False)

Set the value of a list of preferences.

Parameters:
  • prefs – A dict containing one or more preferences and their values to be set. See set_pref() for further details.
  • default_branch – Optional, if True the preference value will be written to the default branch, and will remain until the application gets restarted. Otherwise a user-defined value is set. Defaults to False.

Usage example:

marionette.set_prefs({"browser.tabs.warnOnClose": True})
set_script_timeout(timeout)

Sets the maximum number of ms that an asynchronous script is allowed to run.

If a script does not return in the specified amount of time, a ScriptTimeoutException is raised.

Parameters:timeout – The maximum number of milliseconds an asynchronous script can run without causing an ScriptTimeoutException to be raised

Note

set_script_timeout is deprecated, please use timeout.script setter.

set_search_timeout(timeout)

Sets a timeout for the find methods.

When searching for an element using either find_element() or find_elements(), the method will continue trying to locate the element for up to timeout ms. This can be useful if, for example, the element you’re looking for might not exist immediately, because it belongs to a page which is currently being loaded.

Parameters:timeout – Timeout in milliseconds.

Note

set_search_timeout is deprecated, please use timeout.implicit setter.

set_window_position(x, y)

Set the position of the current window

Parameters:
  • x – x coordinate for the top left of the window
  • y – y coordinate for the top left of the window
set_window_rect(x=None, y=None, height=None, width=None)

Set the position and size of the current window.

The supplied width and height values refer to the window outerWidth and outerHeight values, which include scroll bars, title bars, etc.

An error will be returned if the requested window size would result in the window being in the maximised state.

Parameters:
  • x – x coordinate for the top left of the window
  • y – y coordinate for the top left of the window
  • width – The width to resize the window to.
  • height – The height to resize the window to.
set_window_size(width, height)

Resize the browser window currently in focus.

The supplied width and height values refer to the window outerWidth and outerHeight values, which include scroll bars, title bars, etc.

An error will be returned if the requested window size would result in the window being in the maximised state.

Parameters:
  • width – The width to resize the window to.
  • height – The height to resize the window to.

:returns Window rect.

start_session(*args, **kwargs)

Create a new WebDriver session. This method must be called before performing any other action.

Parameters:
  • capabilities – An optional dictionary of Marionette-recognised capabilities. It does not accept a WebDriver conforming capabilities dictionary (including alwaysMatch, firstMatch, desiredCapabilities, or requriedCapabilities), and only recognises extension capabilities that are specific to Marionette.
  • timeout – Optional timeout in seconds for the server to be ready.
Returns:

A dictionary of the capabilities offered.

switch_to_alert()

Returns an Alert object for interacting with a currently displayed alert.

alert = self.marionette.switch_to_alert()
text = alert.text
alert.accept()
switch_to_default_content()

Switch the current context to page’s default content.

switch_to_frame(frame=None, focus=True)

Switch the current context to the specified frame. Subsequent commands will operate in the context of the specified frame, if applicable.

Parameters:
  • frame – A reference to the frame to switch to. This can be an HTMLElement, an integer index, string name, or an ID attribute. If you call switch_to_frame without an argument, it will switch to the top-level frame.
  • focus – A boolean value which determins whether to focus the frame that we just switched to.
switch_to_parent_frame()

Switch to the Parent Frame

switch_to_shadow_root(host=None)

Switch the current context to the specified host’s Shadow DOM. Subsequent commands will operate in the context of the specified Shadow DOM, if applicable.

Parameters:host – A reference to the host element containing Shadow DOM. This can be an HTMLElement. If you call switch_to_shadow_root without an argument, it will switch to the parent Shadow DOM or the top-level frame.
switch_to_window(window_id, focus=True)

Switch to the specified window; subsequent commands will be directed at the new window.

Parameters:
  • window_id – The id or name of the window to switch to.
  • focus – A boolean value which determins whether to focus the window that we just switched to.
title

Current title of the active window.

using_context(*args, **kwds)

Sets the context that Marionette commands are running in using a with statement. The state of the context on the server is saved before entering the block, and restored upon exiting it.

Parameters:context – Context, may be one of the class properties CONTEXT_CHROME or CONTEXT_CONTENT.

Usage example:

with marionette.using_context(marionette.CONTEXT_CHROME):
    # chrome scope
    ... do stuff ...
using_prefs(*args, **kwds)

Set preferences for code executed in a with block, and restores them on exit.

Parameters:
  • prefs – A dict containing one or more preferences and their values to be set. See set_prefs() for further details.
  • default_branch – Optional, if True the preference value will be written to the default branch, and will remain until the application gets restarted. Otherwise a user-defined value is set. Defaults to False.

Usage example:

with marionette.using_prefs({"browser.tabs.warnOnClose": True}):
    # ... do stuff ...
wait_for_port(timeout=None)

Wait until Marionette server has been created the communication socket.

Parameters:timeout – Timeout in seconds for the server to be ready.
window_handles

Get list of windows in the current context.

If called in the content context it will return a list of references to all available browser windows. Called in the chrome context, it will list all available windows, not just browser windows (e.g. not just navigator.browser).

Each window handle is assigned by the server, and the list of strings returned does not have a guaranteed ordering.

Returns:Unordered list of unique window handles as strings
window_size

Get the current browser window size.

Will return the current browser window size in pixels. Refers to window outerWidth and outerHeight values, which include scroll bars, title bars, etc.

Returns:Window rect.

HTMLElement

class marionette_driver.marionette.HTMLElement(marionette, id)

Represents a DOM Element.

clear()

Clears the input of the element.

click()

Simulates a click on the element.

find_element(method, target)

Returns an HTMLElement instance that matches the specified method and target, relative to the current element.

For more details on this function, see the find_element() method in the Marionette class.

find_elements(method, target)

Returns a list of all HTMLElement instances that match the specified method and target in the current context.

For more details on this function, see the find_elements() method in the Marionette class.

get_attribute(name)

Returns the requested attribute, or None if no attribute is set.

get_property(name)

Returns the requested property, or None if the property is not set.

is_displayed()

Returns True if the element is displayed, False otherwise.

is_enabled()

This command will return False if all the following criteria are met otherwise return True:

  • A form control is disabled.
  • A HTMLElement has a disabled boolean attribute.
is_selected()

Returns True if the element is selected.

location

Get an element’s location on the page.

The returned point will contain the x and y coordinates of the top left-hand corner of the given element. The point (0,0) refers to the upper-left corner of the document.

Returns:a dictionary containing x and y as entries
rect

Gets the element’s bounding rectangle.

This will return a dictionary with the following:

  • x and y represent the top left coordinates of the HTMLElement relative to top left corner of the document.
  • height and the width will contain the height and the width of the DOMRect of the HTMLElement.
send_keys(*strings)

Sends the string via synthesized keypresses to the element. If an array is passed in like marionette.send_keys(Keys.SHIFT, “a”) it will be joined into a string. If an integer is passed in like marionette.send_keys(1234) it will be coerced into a string.

size

A dictionary with the size of the element.

tag_name

The tag name of the element.

tap(x=None, y=None)

Simulates a set of tap events on the element.

Parameters:
  • x – X coordinate of tap event. If not given, default to the centre of the element.
  • y – Y coordinate of tap event. If not given, default to the centre of the element.
text

Returns the visible text of the element, and its child elements.

value_of_css_property(property_name)

Gets the value of the specified CSS property name.

Parameters:property_name – Property name to get the value of.

DateTimeValue

class marionette_driver.DateTimeValue(element)

Interface for setting the value of HTML5 “date” and “time” input elements.

Simple usage example:

element = marionette.find_element(By.ID, "date-test")
dt_value = DateTimeValue(element)
dt_value.date = datetime(1998, 6, 2)
date

Retrieve the element’s string value

time

Retrieve the element’s string value

Actions

class marionette_driver.marionette.Actions(marionette)

An Action object represents a set of actions that are executed in a particular order.

All action methods (press, etc.) return the Actions object itself, to make it easy to create a chain of events.

Example usage:

# get html file
testAction = marionette.absolute_url("testFool.html")
# navigate to the file
marionette.navigate(testAction)
# find element1 and element2
element1 = marionette.find_element(By.ID, "element1")
element2 = marionette.find_element(By.ID, "element2")
# create action object
action = Actions(marionette)
# add actions (press, wait, move, release) into the object
action.press(element1).wait(5). move(element2).release()
# fire all the added events
action.perform()
cancel()

Sends ‘touchcancel’ event to the target of the original ‘touchstart’ event.

May only be called if press() has already be called.

click(element, button=0, count=1)

Performs a click with additional parameters to allow for double clicking, right click, middle click, etc.

Parameters:
  • element – The element to click.
  • button – The mouse button to click (indexed from 0, left to right).
  • count – Optional, the count of clicks to synthesize (for double click events).
context_click(element)

Performs a context click on the specified element.

Parameters:element – The element to context click.
double_click(element)

Performs a double click on the specified element.

Parameters:element – The element to double click.
double_tap(element, x=None, y=None)

Performs a double tap on the target element.

Parameters:
  • element – The element to double tap.
  • x – Optional, x-coordinate of double tap, relative to the top-left corner of the element.
  • y – Optional, y-coordinate of double tap, relative to the top-left corner of the element.
flick(element, x1, y1, x2, y2, duration=200)

Performs a flick gesture on the target element.

Parameters:
  • element – The element to perform the flick gesture on.
  • x1 – Starting x-coordinate of flick, relative to the top left corner of the element.
  • y1 – Starting y-coordinate of flick, relative to the top left corner of the element.
  • x2 – Ending x-coordinate of flick, relative to the top left corner of the element.
  • y2 – Ending y-coordinate of flick, relative to the top left corner of the element.
  • duration – Time needed for the flick gesture for complete (in milliseconds).
key_down(key_code)

Perform a “keyDown” action for the given key code. Modifier keys are respected by the server for the course of an action chain.

Parameters:key_code – The key to press as a result of this action.
key_up(key_code)

Perform a “keyUp” action for the given key code. Modifier keys are respected by the server for the course of an action chain.

Parameters:key_up – The key to release as a result of this action.
long_press(element, time_in_seconds, x=None, y=None)

Performs a long press gesture on the target element.

Parameters:
  • element – The element to press.
  • time_in_seconds – Time in seconds to wait before releasing the press.
  • x – Optional, x-coordinate to tap, relative to the top-left corner of the element.
  • y – Optional, y-coordinate to tap, relative to the top-left corner of the element.

This is equivalent to calling:

action.press(element, x, y).wait(time_in_seconds).release()
middle_click(element)

Performs a middle click on the specified element.

Parameters:element – The element to middle click.
move(element)

Sends a ‘touchmove’ event at the center of the target element.

Parameters:element – Element to move towards.

May only be called if press() has already be called.

move_by_offset(x, y)

Sends ‘touchmove’ event to the given x, y coordinates relative to the top-left of the currently touched element.

May only be called if press() has already be called.

Parameters:
  • x – Specifies x-coordinate of move event, relative to the top-left corner of the element.
  • y – Specifies y-coordinate of move event, relative to the top-left corner of the element.
perform()

Sends the action chain built so far to the server side for execution and clears the current chain of actions.

press(element, x=None, y=None)

Sends a ‘touchstart’ event to this element.

If no coordinates are given, it will be targeted at the center of the element. If given, it will be targeted at the (x,y) coordinates relative to the top-left corner of the element.

Parameters:
  • element – The element to press on.
  • x – Optional, x-coordinate to tap, relative to the top-left corner of the element.
  • y – Optional, y-coordinate to tap, relative to the top-left corner of the element.
release()

Sends a ‘touchend’ event to this element.

May only be called if press() has already be called on this element.

If press and release are chained without a move action between them, then it will be processed as a ‘tap’ event, and will dispatch the expected mouse events (‘mousemove’ (if necessary), ‘mousedown’, ‘mouseup’, ‘mouseclick’) after the touch events. If there is a wait period between press and release that will trigger a contextmenu, then the ‘contextmenu’ menu event will be fired instead of the touch/mouse events.

tap(element, x=None, y=None)

Performs a quick tap on the target element.

Parameters:
  • element – The element to tap.
  • x – Optional, x-coordinate of tap, relative to the top-left corner of the element. If not specified, default to center of element.
  • y – Optional, y-coordinate of tap, relative to the top-left corner of the element. If not specified, default to center of element.

This is equivalent to calling:

action.press(element, x, y).release()
wait(time=None)

Waits for specified time period.

Parameters:time – Time in seconds to wait. If time is None then this has no effect for a single action chain. If used inside a multi-action chain, then time being None indicates that we should wait for all other currently executing actions that are part of the chain to complete.

MultiActions

class marionette_driver.marionette.MultiActions(marionette)

A MultiActions object represents a sequence of actions that may be performed at the same time. Its intent is to allow the simulation of multi-touch gestures. Usage example:

# create multiaction object
multitouch = MultiActions(marionette)
# create several action objects
action_1 = Actions(marionette)
action_2 = Actions(marionette)
# add actions to each action object/finger
action_1.press(element1).move_to(element2).release()
action_2.press(element3).wait().release(element3)
# fire all the added events
multitouch.add(action_1).add(action_2).perform()
add(action)

Adds a set of actions to perform.

Parameters:action – An Actions object.
perform()

Perform all the actions added to this object.

Alert

class marionette_driver.marionette.Alert(marionette)

A class for interacting with alerts.

Alert(marionette).accept()
Alert(marionette).dismiss()
accept()

Accept a currently displayed modal dialog.

dismiss()

Dismiss a currently displayed modal dialog.

send_keys(*string)

Send keys to the currently displayed text input area in an open tab modal dialog.

text

Return the currently displayed text in a tab modal.

Wait

class marionette_driver.Wait(marionette, timeout=None, interval=None, ignored_exceptions=None, clock=None)

An explicit conditional utility class for waiting until a condition evaluates to true or not null.

This will repeatedly evaluate a condition in anticipation for a truthy return value, or its timeout to expire, or its waiting predicate to become true.

A Wait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as errors.NoSuchElementException when searching for an element on the page.

__init__(marionette, timeout=None, interval=None, ignored_exceptions=None, clock=None)

Configure the Wait instance to have a custom timeout, interval, and list of ignored exceptions. Optionally a different time implementation than the one provided by the standard library (time) can also be provided.

Sample usage:

# Wait 30 seconds for window to open, checking for its presence once
# every 5 seconds.
wait = Wait(marionette, timeout=30, interval=5,
            ignored_exceptions=errors.NoSuchWindowException)
window = wait.until(lambda m: m.switch_to_window(42))
Parameters:
  • marionette – The input value to be provided to conditions, usually a Marionette instance.
  • timeout – How long to wait for the evaluated condition to become true. The default timeout is wait.DEFAULT_TIMEOUT.
  • interval – How often the condition should be evaluated. In reality the interval may be greater as the cost of evaluating the condition function. If that is not the case the interval for the next condition function call is shortend to keep the original interval sequence as best as possible. The default polling interval is wait.DEFAULT_INTERVAL.
  • ignored_exceptions – Ignore specific types of exceptions whilst waiting for the condition. Any exceptions not whitelisted will be allowed to propagate, terminating the wait.
  • clock – Allows overriding the use of the runtime’s default time library. See wait.SystemClock for implementation details.
__weakref__

list of weak references to the object (if defined)

until(condition, is_true=None, message='')

Repeatedly runs condition until its return value evaluates to true, or its timeout expires or the predicate evaluates to true.

This will poll at the given interval until the given timeout is reached, or the predicate or conditions returns true. A condition that returns null or does not evaluate to true will fully elapse its timeout before raising an errors.TimeoutException.

If an exception is raised in the condition function and it’s not ignored, this function will raise immediately. If the exception is ignored, it will continue polling for the condition until it returns successfully or a TimeoutException is raised.

Parameters:
  • condition – A callable function whose return value will be returned by this function if it evaluates to true.
  • is_true – An optional predicate that will terminate and return when it evaluates to False. It should be a function that will be passed clock and an end time. The default predicate will terminate a wait when the clock elapses the timeout.
  • message – An optional message to include in the exception’s message if this function times out.

Built-in Conditions

class marionette_driver.expected.element_displayed(*args)

An expectation for checking that an element is visible.

Visibility means that the element is not only displayed, but also has a height and width that is greater than 0 pixels.

Stale elements, meaning elements that have been detached from the DOM of the current context are treated as not being displayed, meaning this expectation is not analogous to the behaviour of calling is_displayed() on an HTMLElement.

You can select which element to be checked for visibility by supplying a locator:

displayed = Wait(marionette).until(expected.element_displayed(By.ID, "foo"))

Or by supplying an element:

el = marionette.find_element(By.ID, "foo")
displayed = Wait(marionette).until(expected.element_displayed(el))
Parameters:args – locator or web element
Returns:True if element is displayed, False if hidden
class marionette_driver.expected.element_enabled(element)

An expectation for checking that the given element is enabled.

Parameters:element – the element to check if enabled
Returns:True if element is enabled, False otherwise
class marionette_driver.expected.element_not_displayed(*args)

An expectation for checking that an element is not visible.

Visibility means that the element is not only displayed, but also has a height and width that is greater than 0 pixels.

Stale elements, meaning elements that have been detached fom the DOM of the current context are treated as not being displayed, meaning this expectation is not analogous to the behaviour of calling is_displayed() on an HTMLElement.

You can select which element to be checked for visibility by supplying a locator:

hidden = Wait(marionette).until(expected.element_not_displayed(By.ID, "foo"))

Or by supplying an element:

el = marionette.find_element(By.ID, "foo")
hidden = Wait(marionette).until(expected.element_not_displayed(el))
Parameters:args – locator or web element
Returns:True if element is hidden, False if displayed
class marionette_driver.expected.element_not_enabled(element)

An expectation for checking that the given element is disabled.

Parameters:element – the element to check if disabled
Returns:True if element is disabled, False if enabled
class marionette_driver.expected.element_not_present(*args)

Checks that a web element is not present in the DOM of the current context.

You can select which element to be checked for lack of presence by supplying a locator:

r = Wait(marionette).until(expected.element_not_present(By.ID, "foo"))

Or by using a function/lambda returning an element:

r = Wait(marionette).until(
    expected.element_present(lambda m: m.find_element(By.ID, "foo")))
Parameters:args – locator or function returning web element
Returns:True if element is not present, or False if it is present
class marionette_driver.expected.element_not_selected(element)

An expectation for checking that the given element is not selected.

Parameters:element – the element to not be selected
Returns:True if element is not selected, False if selected
class marionette_driver.expected.element_present(*args)

Checks that a web element is present in the DOM of the current context. This does not necessarily mean that the element is visible.

You can select which element to be checked for presence by supplying a locator:

el = Wait(marionette).until(expected.element_present(By.ID, "foo"))

Or by using a function/lambda returning an element:

el = Wait(marionette).until(
    expected.element_present(lambda m: m.find_element(By.ID, "foo")))
Parameters:args – locator or function returning web element
Returns:the web element once it is located, or False
class marionette_driver.expected.element_selected(element)

An expectation for checking that the given element is selected.

Parameters:element – the element to be selected
Returns:True if element is selected, False otherwise
class marionette_driver.expected.element_stale(element)

Check that the given element is no longer attached to DOM of the current context.

This can be useful for waiting until an element is no longer present.

Sample usage:

el = marionette.find_element(By.ID, "foo")
# ...
Wait(marionette).until(expected.element_stale(el))
Parameters:element – the element to wait for
Returns:False if the element is still attached to the DOM, True otherwise
class marionette_driver.expected.elements_not_present(*args)

Checks that web elements are not present in the DOM of the current context.

You can select which elements to be checked for not being present by supplying a locator:

r = Wait(marionette).until(expected.elements_not_present(By.TAG_NAME, "a"))

Or by using a function/lambda returning a list of elements:

r = Wait(marionette).until(
    expected.elements_not_present(lambda m: m.find_elements(By.TAG_NAME, "a")))
Parameters:args – locator or function returning a list of web elements
Returns:True if elements are missing, False if one or more are present
class marionette_driver.expected.elements_present(*args)

Checks that web elements are present in the DOM of the current context. This does not necessarily mean that the elements are visible.

You can select which elements to be checked for presence by supplying a locator:

els = Wait(marionette).until(expected.elements_present(By.TAG_NAME, "a"))

Or by using a function/lambda returning a list of elements:

els = Wait(marionette).until(
    expected.elements_present(lambda m: m.find_elements(By.TAG_NAME, "a")))
Parameters:args – locator or function returning a list of web elements
Returns:list of web elements once they are located, or False

Timeouts

class marionette_driver.timeout.Timeouts(marionette)

Manage timeout settings in the Marionette session.

Usage:

marionette = Marionette(...)
marionette.start_session()
marionette.timeout.page_load = 10
marionette.timeout.page_load
# => 10
implicit

Get the session’s implicit wait timeout. This specifies the time to wait for the implicit element location strategy when retrieving elements. It is by default disabled (0 seconds).

page_load

Get the session’s page load timeout. This specifies the time to wait for the page loading to complete. It is by default 5 minutes (or 300 seconds).

reset()

Resets timeouts to their default values.

script

Get the session’s script timeout. This specifies the time to wait for injected scripts to finished before interrupting them. It is by default 30 seconds.

Addons

class marionette_driver.addons.Addons(marionette)

An API for installing and inspecting addons during Gecko runtime. This is a partially implemented wrapper around Gecko’s AddonManager API.

For example:

from marionette_driver.addons import Addons
addons = Addons(marionette)
addons.install("/path/to/extension.xpi")
install(path, temp=False)

Install a Firefox addon.

If the addon is restartless, it can be used right away. Otherwise a restart using restart() will be needed.

Parameters:
  • path – A file path to the extension to be installed.
  • temp – Install a temporary addon. Temporary addons will automatically be uninstalled on shutdown and do not need to be signed, though they must be restartless.
Returns:

The addon ID string of the newly installed addon.

Raises:

AddonInstallException

uninstall(addon_id)

Uninstall a Firefox addon.

If the addon is restartless, it will be uninstalled right away. Otherwise a restart using restart() will be needed.

If the call to uninstall is resulting in a ScriptTimeoutException, an invalid ID is likely being passed in. Unfortunately due to AddonManager’s implementation, it’s hard to retrieve this error from Python.

Parameters:addon_id – The addon ID string to uninstall.

Localization

class marionette_driver.localization.L10n(marionette)

An API which allows Marionette to handle localized content.

The localization of UI elements in Gecko based applications is done via entities and properties. For static values entities are used, which are located in .dtd files. Whereby for dynamically updated content the values come from .property files. Both types of elements can be identifed via a unique id, and the translated content retrieved.

For example:

from marionette_driver.localization import L10n
l10n = L10n(marionette)

l10n.localize_entity(["chrome://global/locale/about.dtd"], "about.version")
l10n.localize_property(["chrome://global/locale/findbar.properties"], "FastFind"))
localize_entity(dtd_urls, entity_id)

Retrieve the localized string for the specified entity id.

Parameters:
  • dtd_urls – List of .dtd URLs which will be used to search for the entity.
  • entity_id – ID of the entity to retrieve the localized string for.
Returns:

The localized string for the requested entity.

Raises:

NoSuchElementException

localize_property(properties_urls, property_id)

Retrieve the localized string for the specified property id.

Parameters:
  • properties_urls – List of .properties URLs which will be used to search for the property.
  • property_id – ID of the property to retrieve the localized string for.
Returns:

The localized string for the requested property.

Raises:

NoSuchElementException