6. WebDriver API

Note

This is not an official documentation. Official API documentation is available here.

This chapter cover all the interfaces of Selenium WebDriver.

Recommended Import Style

The API definitions in this chapter shows the absolute location of classes. However the recommended import style is as given below:

from selenium import webdriver

Then, you can access the classes like this:

webdriver.Firefox
webdriver.FirefoxProfile
webdriver.Chrome
webdriver.ChromeOptions
webdriver.Ie
webdriver.Opera
webdriver.PhantomJS
webdriver.Remote
webdriver.DesiredCapabilities
webdriver.ActionChains
webdriver.TouchActions
webdriver.Proxy

The special keys class (Keys) can be imported like this:

from selenium.webdriver.common.keys import Keys

The exception classes can be imported like this (Replace the TheNameOfTheExceptionClass with actual class name given below):

from selenium.common.exceptions import [TheNameOfTheExceptionClass]

Conventions used in the API

Some attributes are callable (or methods) and others are non-callable (properties). All the callable attributes are ending with round brackets.

Here is an example for property:

  • current_url

    URL of the current loaded page.

    Usage:

    driver.current_url
    

Here is an example for a method:

  • close()

    Closes the current window.

    Usage:

    driver.close()
    

6.1. Exceptions

Exceptions that may happen in all the webdriver code.

exception selenium.common.exceptions.ElementNotSelectableException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.InvalidElementStateException

exception selenium.common.exceptions.ElementNotVisibleException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.InvalidElementStateException

Thrown to indicate that although an element is present on the DOM, it is not visible, and so is not able to be interacted with.

exception selenium.common.exceptions.ErrorInResponseException(response, msg)

Bases: selenium.common.exceptions.WebDriverException

An error has occurred on the server side.

This may happen when communicating with the firefox extension or the remote driver server.

exception selenium.common.exceptions.ImeActivationFailedException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Indicates that activating an IME engine has failed.

exception selenium.common.exceptions.ImeNotAvailableException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Indicates that IME support is not available. This exception is thrown for every IME-related method call if IME support is not available on the machine.

exception selenium.common.exceptions.InvalidCookieDomainException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when attempting to add a cookie under a different domain than the current URL.

exception selenium.common.exceptions.InvalidElementStateException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

exception selenium.common.exceptions.InvalidSelectorException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.NoSuchElementException

Thrown when the selector which is used to find an element does not return a WebElement. Currently this only happens when the selector is an xpath expression is used which is either syntactically invalid (i.e. it is not a xpath expression) or the expression does not select WebElements (e.g. “count(//input)”).

exception selenium.common.exceptions.InvalidSwitchToTargetException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

The frame or window target to be switched doesn’t exist.

exception selenium.common.exceptions.MoveTargetOutOfBoundsException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Indicates that the target provided to the actions move() method is invalid

exception selenium.common.exceptions.NoAlertPresentException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

exception selenium.common.exceptions.NoSuchAttributeException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

find_element_by_* can’t find the element.

exception selenium.common.exceptions.NoSuchElementException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

find_element_by_* can’t find the element.

exception selenium.common.exceptions.NoSuchFrameException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.InvalidSwitchToTargetException

exception selenium.common.exceptions.NoSuchWindowException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.InvalidSwitchToTargetException

exception selenium.common.exceptions.RemoteDriverServerException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

exception selenium.common.exceptions.StaleElementReferenceException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Indicates that a reference to an element is now “stale” — the element no longer appears on the DOM of the page.

exception selenium.common.exceptions.TimeoutException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when a command does not complete in enough time.

exception selenium.common.exceptions.UnableToSetCookieException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when a driver fails to set a cookie.

exception selenium.common.exceptions.UnexpectedTagNameException(msg=None, screen=None, stacktrace=None)

Bases: selenium.common.exceptions.WebDriverException

Thrown when a support class did not get an expected web element

exception selenium.common.exceptions.WebDriverException(msg=None, screen=None, stacktrace=None)

Bases: exceptions.Exception

6.2. Action Chains

The ActionChains implementation

class selenium.webdriver.common.action_chains.ActionChains(driver)

Bases: object

Generate user actions. All actions are stored in the ActionChains object. Call perform() to fire stored actions.

click(on_element=None)

Clicks an element.

Args :
  • on_element: The element to click. If None, clicks on current mouse position.
click_and_hold(on_element=None)

Holds down the left mouse button on an element.

Args :
  • on_element: The element to mouse down. If None, clicks on current mouse position.
context_click(on_element=None)

Performs a context-click (right click) on an element.

Args :
  • on_element: The element to context-click. If None, clicks on current mouse position.
double_click(on_element=None)

Double-clicks an element.

Args :
  • on_element: The element to double-click. If None, clicks on current mouse position.
drag_and_drop(source, target)
Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args :
  • source: The element to mouse down.
  • target: The element to mouse up.
drag_and_drop_by_offset(source, xoffset, yoffset)
Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args :
  • source: The element to mouse down.
  • xoffset: X offset to move to.
  • yoffset: Y offset to move to.
key_down(value, element=None)

Sends a key press only, without releasing it. Should only be used with modifier keys (Control, Alt and Shift).

Args :
  • key: The modifier key to send. Values are defined in Keys class.
  • target: The element to send keys. If None, sends a key to current focused element.
key_up(value, element=None)

Releases a modifier key.

Args :
  • key: The modifier key to send. Values are defined in Keys class.
  • target: The element to send keys. If None, sends a key to current focused element.
move_by_offset(xoffset, yoffset)

Moving the mouse to an offset from current mouse position.

Args :
  • xoffset: X offset to move to.
  • yoffset: Y offset to move to.
move_to_element(to_element)

Moving the mouse to the middle of an element.

Args :
  • to_element: The element to move to.
move_to_element_with_offset(to_element, xoffset, yoffset)

Move the mouse by an offset of the specificed element. Offsets are relative to the top-left corner of the element.

Args :
  • to_element: The element to move to.
  • xoffset: X offset to move to.
  • yoffset: Y offset to move to.
perform()

Performs all stored actions.

release(on_element=None)

Releasing a held mouse button.

Args :
  • on_element: The element to mouse up.
send_keys(*keys_to_send)

Sends keys to current focused element.

Args :
  • keys_to_send: The keys to send.
send_keys_to_element(element, *keys_to_send)

Sends keys to an element.

Args :
  • element: The element to send keys.
  • keys_to_send: The keys to send.

6.3. Alerts

class selenium.webdriver.common.alert.Alert(driver)

Bases: object

accept()

Accepts the alert available

dismiss()

Dismisses the alert available

send_keys(keysToSend)

Send Keys to the Alert

text

Gets the text of the Alert

6.4. Special Keys

class selenium.webdriver.common.keys.Keys

Bases: object

ADD = u'\ue025'
ALT = u'\ue00a'
ARROW_DOWN = u'\ue015'
ARROW_LEFT = u'\ue012'
ARROW_RIGHT = u'\ue014'
ARROW_UP = u'\ue013'
BACK_SPACE = u'\ue003'
CANCEL = u'\ue001'
CLEAR = u'\ue005'
COMMAND = u'\ue03d'
CONTROL = u'\ue009'
DECIMAL = u'\ue028'
DELETE = u'\ue017'
DIVIDE = u'\ue029'
DOWN = u'\ue015'
END = u'\ue010'
ENTER = u'\ue007'
EQUALS = u'\ue019'
ESCAPE = u'\ue00c'
F1 = u'\ue031'
F10 = u'\ue03a'
F11 = u'\ue03b'
F12 = u'\ue03c'
F2 = u'\ue032'
F3 = u'\ue033'
F4 = u'\ue034'
F5 = u'\ue035'
F6 = u'\ue036'
F7 = u'\ue037'
F8 = u'\ue038'
F9 = u'\ue039'
HELP = u'\ue002'
HOME = u'\ue011'
INSERT = u'\ue016'
LEFT = u'\ue012'
LEFT_ALT = u'\ue00a'
LEFT_CONTROL = u'\ue009'
LEFT_SHIFT = u'\ue008'
META = u'\ue03d'
MULTIPLY = u'\ue024'
NULL = u'\ue000'
NUMPAD0 = u'\ue01a'
NUMPAD1 = u'\ue01b'
NUMPAD2 = u'\ue01c'
NUMPAD3 = u'\ue01d'
NUMPAD4 = u'\ue01e'
NUMPAD5 = u'\ue01f'
NUMPAD6 = u'\ue020'
NUMPAD7 = u'\ue021'
NUMPAD8 = u'\ue022'
NUMPAD9 = u'\ue023'
PAGE_DOWN = u'\ue00f'
PAGE_UP = u'\ue00e'
PAUSE = u'\ue00b'
RETURN = u'\ue006'
RIGHT = u'\ue014'
SEMICOLON = u'\ue018'
SEPARATOR = u'\ue026'
SHIFT = u'\ue008'
SPACE = u'\ue00d'
SUBTRACT = u'\ue027'
TAB = u'\ue004'
UP = u'\ue013'

6.5. Firefox WebDriver

class selenium.webdriver.firefox.webdriver.WebDriver(firefox_profile=None, firefox_binary=None, timeout=30, capabilities=None, proxy=None)

Bases: selenium.webdriver.remote.webdriver.WebDriver

create_web_element(element_id)

Override from RemoteWebDriver to use firefox.WebElement.

quit()

Quits the driver and close every associated window.

NATIVE_EVENTS_ALLOWED = True
firefox_profile

6.6. Chrome WebDriver

class selenium.webdriver.chrome.webdriver.WebDriver(executable_path='chromedriver', port=0, chrome_options=None, service_args=None, desired_capabilities=None, service_log_path=None)

Bases: selenium.webdriver.remote.webdriver.WebDriver

Controls the ChromeDriver and allows you to drive the browser.

You will need to download the ChromeDriver executable from http://code.google.com/p/chromedriver/downloads/list

quit()

Closes the browser and shuts down the ChromeDriver executable that is started when starting the ChromeDriver

6.7. Remote WebDriver

The WebDriver implementation.

class selenium.webdriver.remote.webdriver.WebDriver(command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=None, browser_profile=None, proxy=None)

Bases: object

Controls a browser by sending commands to a remote server. This server is expected to be running the WebDriver wire protocol as defined here: http://code.google.com/p/selenium/wiki/JsonWireProtocol

Attributes :
  • command_executor - The command.CommandExecutor object used to execute commands.
  • error_handler - errorhandler.ErrorHandler object used to verify that the server did not return an error.
  • session_id - The session ID to send with every command.
  • capabilities - A dictionary of capabilities of the underlying browser for this instance’s session.
  • proxy - A selenium.webdriver.common.proxy.Proxy object, to specify a proxy for the browser to use.

Adds a cookie to your current session.

Args :
  • cookie_dict: A dictionary object, with required keys - “name” and “value”;

    optional keys - “path”, “domain”, “secure”, “expiry”

Usage:
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})
back()

Goes one step backward in the browser history.

Usage :driver.back()
close()

Closes the current window.

Usage :driver.close()
create_web_element(element_id)

Creates a web element with the specified element_id.

delete_all_cookies()

Delete all cookies in the scope of the session.

Usage :driver.delete_all_cookies()

Deletes a single cookie with the given name.

Usage :driver.delete_cookie(‘my_cookie’)
execute(driver_command, params=None)

Sends a command to be executed by a command.CommandExecutor.

Args :
  • driver_command: The name of the command to execute as a string.
  • params: A dictionary of named parameters to send with the command.
Returns :

The command’s JSON response loaded into a dictionary object.

execute_async_script(script, *args)

Asynchronously Executes JavaScript in the current window/frame.

Args :
  • script: The JavaScript to execute.
  • *args: Any applicable arguments for your JavaScript.
Usage :

driver.execute_async_script(‘document.title’)

execute_script(script, *args)

Synchronously Executes JavaScript in the current window/frame.

Args :
  • script: The JavaScript to execute.
  • *args: Any applicable arguments for your JavaScript.
Usage :

driver.execute_script(‘document.title’)

find_element(by='id', value=None)

‘Private’ method used by the find_element_by_* methods.

Usage :Use the corresponding find_element_by_* instead of this.
find_element_by_class_name(name)

Finds an element by class name.

Args :
  • name: The class name of the element to find.
Usage :

driver.find_element_by_class_name(‘foo’)

find_element_by_css_selector(css_selector)

Finds an element by css selector.

Args :
  • css_selector: The css selector to use when finding elements.
Usage :

driver.find_element_by_css_selector(‘#foo’)

find_element_by_id(id_)

Finds an element by id.

Args :
  • id_ - The id of the element to be found.
Usage :

driver.find_element_by_id(‘foo’)

Finds an element by link text.

Args :
  • link_text: The text of the element to be found.
Usage :

driver.find_element_by_link_text(‘Sign In’)

find_element_by_name(name)

Finds an element by name.

Args :
  • name: The name of the element to find.
Usage :

driver.find_element_by_name(‘foo’)

Finds an element by a partial match of its link text.

Args :
  • link_text: The text of the element to partially match on.
Usage :

driver.find_element_by_partial_link_text(‘Sign’)

find_element_by_tag_name(name)

Finds an element by tag name.

Args :
  • name: The tag name of the element to find.
Usage :

driver.find_element_by_tag_name(‘foo’)

find_element_by_xpath(xpath)

Finds an element by xpath.

Args :
  • xpath - The xpath locator of the element to find.
Usage :

driver.find_element_by_xpath(‘//div/td[1]’)

find_elements(by='id', value=None)

‘Private’ method used by the find_elements_by_* methods.

Usage :Use the corresponding find_elements_by_* instead of this.
find_elements_by_class_name(name)

Finds elements by class name.

Args :
  • name: The class name of the elements to find.
Usage :

driver.find_elements_by_class_name(‘foo’)

find_elements_by_css_selector(css_selector)

Finds elements by css selector.

Args :
  • css_selector: The css selector to use when finding elements.
Usage :

driver.find_element_by_css_selector(‘#foo’)

find_elements_by_id(id_)

Finds multiple elements by id.

Args :
  • id_ - The id of the elements to be found.
Usage :

driver.find_element_by_id(‘foo’)

Finds elements by link text.

Args :
  • link_text: The text of the elements to be found.
Usage :

driver.find_elements_by_link_text(‘Sign In’)

find_elements_by_name(name)

Finds elements by name.

Args :
  • name: The name of the elements to find.
Usage :

driver.find_elements_by_name(‘foo’)

Finds elements by a partial match of their link text.

Args :
  • link_text: The text of the element to partial match on.
Usage :

driver.find_element_by_partial_link_text(‘Sign’)

find_elements_by_tag_name(name)

Finds elements by tag name.

Args :
  • name: The tag name the use when finding elements.
Usage :

driver.find_elements_by_tag_name(‘foo’)

find_elements_by_xpath(xpath)

Finds multiple elements by xpath.

Args :
  • xpath - The xpath locator of the elements to be found.
Usage :

driver.find_elements_by_xpath(“//div[contains(@class, ‘foo’)]”)

forward()

Goes one step forward in the browser history.

Usage :driver.forward()
get(url)

Loads a web page in the current browser session.

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

Usage :driver.get_cookie(‘my_cookie’)
get_cookies()

Returns a set of dictionaries, corresponding to cookies visible in the current session.

Usage :driver.get_cookies()
get_screenshot_as_base64()
Gets the screenshot of the current window as a base64 encoded string
which is useful in embedded images in HTML.
Usage :driver.get_screenshot_as_base64()
get_screenshot_as_file(filename)
Gets the screenshot of the current window. Returns False if there is
any IOError, else returns True. Use full paths in your filename.
Args :
  • filename: The full path you wish to save your screenshot to.
Usage :

driver.get_screenshot_as_file(‘/Screenshots/foo.png’)

get_window_position(windowHandle='current')

Gets the x,y position of the current window.

Usage :driver.get_window_position()
get_window_size(windowHandle='current')

Gets the width and height of the current window.

Usage :driver.get_window_size()
implicitly_wait(time_to_wait)
Sets a sticky timeout to implicitly wait for an element to be found,
or a command to complete. This method only needs to be called one time per session. To set the timeout for calls to execute_async_script, see set_script_timeout.
Args :
  • time_to_wait: Amount of time to wait (in seconds)
Usage :

driver.implicitly_wait(30)

is_online()

Returns a boolean if the browser is online or offline

maximize_window()

Maximizes the current window that webdriver is using

quit()

Quits the driver and closes every associated window.

Usage :driver.quit()
refresh()

Refreshes the current page.

Usage :driver.refresh()
save_screenshot(filename)

Gets the screenshot of the current window. Returns False if there is any IOError, else returns True. Use full paths in your filename.

set_page_load_timeout(time_to_wait)
Set the amount of time to wait for a page load to complete
before throwing an error.
Args :
  • time_to_wait: The amount of time to wait
Usage :

driver.set_page_load_timeout(30)

set_script_timeout(time_to_wait)
Set the amount of time that the script should wait during an
execute_async_script call before throwing an error.
Args :
  • time_to_wait: The amount of time to wait (in seconds)
Usage :

driver.set_script_timeout(30)

set_window_position(x, y, windowHandle='current')

Sets the x,y position of the current window. (window.moveTo)

Args :
  • x: the x-coordinate in pixels to set the window position
  • y: the y-coordinate in pixels to set the window position
Usage :

driver.set_window_position(0,0)

set_window_size(width, height, windowHandle='current')

Sets the width and height of the current window. (window.resizeTo)

Args :
  • width: the width in pixels to set the window to
  • height: the height in pixels to set the window to
Usage :

driver.set_window_size(800,600)

start_client()

Called before starting a new session. This method may be overridden to define custom startup behavior.

start_session(desired_capabilities, browser_profile=None)

Creates a new session with the desired capabilities.

Args :
  • browser_name - The name of the browser to request.
  • version - Which browser version to request.
  • platform - Which platform to request the browser on.
  • javascript_enabled - Whether the new session should support JavaScript.
  • browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested.
stop_client()

Called after executing a quit command. This method may be overridden to define custom shutdown behavior.

switch_to_active_element()

Returns the element with focus, or BODY if nothing has focus.

Usage :driver.switch_to_active_element()
switch_to_alert()

Switches focus to an alert on the page.

Usage :driver.switch_to_alert()
switch_to_default_content()

Switch focus to the default frame.

Usage :driver.switch_to_default_content()
switch_to_frame(frame_reference)

Switches focus to the specified frame, by index, name, or webelement.

Args :
  • frame_reference: The name of the window to switch to, an integer representing the index,

    or a webelement that is an (i)frame to switch to.

Usage :

driver.switch_to_frame(‘frame_name’) driver.switch_to_frame(1) driver.switch_to_frame(driver.find_elements_by_tag_name(“iframe”)[0])

switch_to_window(window_name)

Switches focus to the specified window.

Args :
  • window_name: The name or window handle of the window to switch to.
Usage :

driver.switch_to_window(‘main’)

application_cache

Returns a ApplicationCache Object to interact with the browser app cache

current_url

Gets the URL of the current page.

Usage :driver.current_url
current_window_handle

Returns the handle of the current window.

Usage :driver.current_window_handle
desired_capabilities

returns the drivers current desired capabilities being used

name

Returns the name of the underlying browser for this instance.

Usage :
  • driver.name
orientation

Gets the current orientation of the device

Usage :orientation = driver.orientation
page_source

Gets the source of the current page.

Usage :driver.page_source
title

Returns the title of the current page.

Usage :driver.title
window_handles

Returns the handles of all windows within the current session.

Usage :driver.window_handles

6.8. WebElement

WebElement implementation.

class selenium.webdriver.remote.webelement.LocalFileDetector

Bases: object

classmethod is_local_file(*keys)
class selenium.webdriver.remote.webelement.WebElement(parent, id_)

Bases: object

Represents an HTML element.

Generally, all interesting operations to do with interacting with a page will be performed through this interface.

clear()

Clears the text if it’s a text entry element.

click()

Clicks the element.

find_element(by='id', value=None)
find_element_by_class_name(name)

Finds an element by their class name.

find_element_by_css_selector(css_selector)

Find and return an element by CSS selector.

find_element_by_id(id_)

Finds element by id.

Finds element by link text.

find_element_by_name(name)

Find element by name.

find_element_by_tag_name(name)
find_element_by_xpath(xpath)

Finds element by xpath.

find_elements(by='id', value=None)
find_elements_by_class_name(name)

Finds elements by their class name.

find_elements_by_css_selector(css_selector)

Find and return list of multiple elements by CSS selector.

find_elements_by_id(id_)
find_elements_by_name(name)
find_elements_by_tag_name(name)
find_elements_by_xpath(xpath)

Finds elements within the elements by xpath.

get_attribute(name)

Gets the attribute value.

is_displayed()

Whether the element would be visible to a user

is_enabled()

Whether the element is enabled.

is_selected()

Whether the element is selected.

send_keys(*value)

Simulates typing into the element.

submit()

Submits a form.

value_of_css_property(property_name)

Returns the value of a CSS property

id
location

Returns the location of the element in the renderable canvas

location_once_scrolled_into_view

CONSIDERED LIABLE TO CHANGE WITHOUT WARNING. Use this to discover where on the screen an element is so that we can click it. This method should cause the element to be scrolled into view.

Returns the top lefthand corner location on the screen, or None if the element is not visible

parent
size

Returns the size of the element

tag_name

Gets this element’s tagName property.

text

Gets the text of the element.

Project Versions

Table Of Contents

Previous topic

5. Test Design Considerations

Next topic

7. Appendix: Frequently asked questions

This Page