7. WebDriver API

Note

这不是一个官方的文档. 但是你可以在这访问官方文档:官方文档.

这一章包含所有的 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:

  1. from selenium import webdriver

Then, you can access the classes like this:

  1. webdriver.Firefox
  2. webdriver.FirefoxProfile
  3. webdriver.Chrome
  4. webdriver.ChromeOptions
  5. webdriver.Ie
  6. webdriver.Opera
  7. webdriver.PhantomJS
  8. webdriver.Remote
  9. webdriver.DesiredCapabilities
  10. webdriver.ActionChains
  11. webdriver.TouchActions
  12. webdriver.Proxy

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

  1. from selenium.webdriver.common.keys import Keys

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

  1. 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 roundbrackets.

Here is an example for property:

- current_urlURL of the current loaded page.Usage:

  1. driver.current_url


Here is an example for a method:

- close()Closes the current window.Usage:

  1. driver.close()


7.1. Exceptions

Exceptions that may happen in all the webdriver code.

Thrown when an element is present in the DOM but interactionswith that element will hit another element do to paint order

Thrown when trying to select an unselectable element.

For example, selecting a ‘script’ element.

Thrown when an element is present on the DOM, butit is not visible, and so is not able to be interacted with.

Most commonly encountered when trying to click or read textof an element that is hidden from view.

Thrown when an error has occurred on the server side.

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

Thrown when activating an IME engine has failed.

Thrown when IME support is not available. This exception is thrown for every IME-relatedmethod call if IME support is not available on the machine.

The arguments passed to a command are either invalid or malformed.

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

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

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

Thrown when the target provided to the ActionsChains move()method is invalid, i.e. out of document.

Thrown when switching to no presented alert.

This can be caused by calling an operation on the Alert() class when an alert isnot yet on the screen.

Thrown when the attribute of element could not be found.

You may want to check if the attribute exists in the particular browser you aretesting against. Some browsers may have different property names for the sameproperty. (IE8’s .innerText vs. Firefox .textContent)

Thrown when element could not be found.

  • If you encounter this exception, you may want to check the following:
    • Check your selector used in your find_by…
    • Element may not yet be on the screen at the time of the find operation,(webpage is still loading) see selenium.webdriver.support.wait.WebDriverWait()for how to write a wait wrapper to wait for an element to appear.
    • exception selenium.common.exceptions.NoSuchFrameException(msg=None, screen=None, stacktrace=None)
    • Bases: selenium.common.exceptions.InvalidSwitchToTargetException

Thrown when frame target to be switched doesn’t exist.

Thrown when window target to be switched doesn’t exist.

To find the current set of active window handles, you can get a listof the active window handles in the following way:

  1. print driver.window_handles

Thrown when a reference to an element is now “stale”.

Stale means the element no longer appears on the DOM of the page.

  • Possible causes of StaleElementReferenceException include, but not limited to:
    • You are no longer on the same page, or the page may have refreshed since the elementwas located.
    • The element may have been removed and re-added to the screen, since it was located.Such as an element being relocated.This can happen typically with a javascript framework when values are updated and thenode is rebuilt.
    • Element may have been inside an iframe or another context which was refreshed.
    • 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.

Thrown when a driver fails to set a cookie.

Thrown when an unexpected alert is appeared.

Usually raised when when an expected modal is blocking webdriver form executing anymore commands.

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

Base webdriver exception.

7.2. Action Chains

The ActionChains implementation,

  • class selenium.webdriver.common.actionchains.ActionChains(_driver)
  • Bases: object

ActionChains are a way to automate low level interactions such asmouse movements, mouse button actions, key press, and context menu interactions.This is useful for doing more complex actions like hover over and drag and drop.

  • Generate user actions.
  • When you call methods for actions on the ActionChains object,the actions are stored in a queue in the ActionChains object.When you call perform(), the events are fired in the order theyare queued up.
    ActionChains can be used in a chain pattern:
  1. menu = driver.find_element_by_css_selector(".nav")
  2. hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")
  3.  
  4. ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()

Or actions can be queued up one by one, then performed.:

  1. menu = driver.find_element_by_css_selector(".nav")
  2. hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")
  3.  
  4. actions = ActionChains(driver)
  5. actions.move_to_element(menu)
  6. actions.click(hidden_submenu)
  7. actions.perform()

Either way, the actions are performed in the order they are called, one afteranother.

  • click(on_element=None)
  • Clicks an element.

Args:

  1. - on_element: The element to click.If None, clicks on current mouse position.
  • clickand_hold(_on_element=None)
  • Holds down the left mouse button on an element.

Args:

  1. - on_element: The element to mouse down.If None, clicks on current mouse position.
  • contextclick(_on_element=None)
  • Performs a context-click (right click) on an element.

Args:

  1. - on_element: The element to context-click.If None, clicks on current mouse position.
  • doubleclick(_on_element=None)
  • Double-clicks an element.

Args:

  1. - on_element: The element to double-click.If None, clicks on current mouse position.
  • dragand_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.
  • dragand_drop_by_offset(_source, xoffset, yoffset)

    • Holds down the left mouse button on the source element,
    • then moves to the target offset and releases the mouse button.
      Args:
    • source: The element to mouse down.
    • xoffset: X offset to move to.
    • yoffset: Y offset to move to.
  • keydown(_value, element=None)

    • Sends a key press only, without releasing it.
    • Should only be used with modifier keys (Control, Alt and Shift).
      Args:
    • value: The modifier key to send. Values are defined in Keys class.
    • element: The element to send keys.If None, sends a key to current focused element.

Example, pressing ctrl+c:

  1. ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
  • keyup(_value, element=None)
  • Releases a modifier key.

Args:

  1. - value: The modifier key to send. Values are defined in Keys class.
  2. - element: The element to send keys.If None, sends a key to current focused element.

Example, pressing ctrl+c:

  1. ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
  • moveby_offset(_xoffset, yoffset)
  • Moving the mouse to an offset from current mouse position.

Args:

  1. - xoffset: X offset to move to, as a positive or negative integer.
  2. - yoffset: Y offset to move to, as a positive or negative integer.
  • moveto_element(_to_element)
  • Moving the mouse to the middle of an element.

Args:

  1. - to_element: The WebElement to move to.
  • moveto_element_with_offset(_to_element, xoffset, yoffset)
    • Move the mouse by an offset of the specified element.
    • Offsets are relative to the top-left corner of the element.
      Args:
    • to_element: The WebElement to move to.
    • xoffset: X offset to move to.
    • yoffset: Y offset to move to.
  • pause(seconds)

  • Pause all inputs for the specified duration in seconds

  • perform()

  • Performs all stored actions.

  • release(on_element=None)

  • Releasing a held mouse button on an element.

Args:

  1. - on_element: The element to mouse up.If None, releases on current mouse position.
  • reset_actions()
  • Clears actions that are already stored on the remote end.

  • sendkeys(*keysto_send)

  • Sends keys to current focused element.

Args:

  1. - keys_to_send: The keys to send. Modifier keys constants can be found in theKeys class.
  • sendkeys_to_element(_element, *keys_to_send)
  • Sends keys to an element.

Args:

  1. - element: The element to send keys.
  2. - keys_to_send: The keys to send. Modifier keys constants can be found in theKeys class.

7.3. Alerts

The Alert implementation.

  • class selenium.webdriver.common.alert.Alert(driver)
  • Bases: object

Allows to work with alerts.

Use this class to interact with alert prompts. It contains methods for dismissing,accepting, inputting, and getting text from alert prompts.

Accepting / Dismissing alert prompts:

  1. Alert(driver).accept()
  2. Alert(driver).dismiss()

Inputting a value into an alert prompt:

name_prompt = Alert(driver)
name_prompt.send_keys(“Willian Shakesphere”)
name_prompt.accept()

Reading a the text of a prompt for verification:

alert_text = Alert(driver).text
self.assertEqual(“Do you wish to quit?”, alert_text)

  • accept()
  • Accepts the alert available.

Usage::Alert(driver).accept() # Confirm a alert dialog.

  • authenticate(username, password)
  • Send the username / password to an Authenticated dialog (like with Basic HTTP Auth).Implicitly ‘clicks ok’

Usage::driver.switch_to.alert.authenticate(‘cheese’, ‘secretGouda’)

Args:-username: string to be set in the username section of the dialog-password: string to be set in the password section of the dialog

  • dismiss()
  • Dismisses the alert available.

  • sendkeys(_keysToSend)

  • Send Keys to the Alert.

Args:

  1. - keysToSend: The text to be sent to Alert.
  • text
  • Gets the text of the Alert.

7.4. Special Keys

The Keys implementation.

  • class selenium.webdriver.common.keys.Keys
  • Bases: object

Set of special keys codes.

  • ADD = u'\ue025'
  • ALT = u'\ue00a'
  • ARROWDOWN = u'\ue015'_
  • ARROWLEFT = u'\ue012'_
  • ARROWRIGHT = u'\ue014'_
  • ARROWUP = u'\ue013'_
  • BACKSPACE = u'\ue003'
  • BACKSPACE = 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'
  • LEFTALT = u'\ue00a'_
  • LEFTCONTROL = u'\ue009'_
  • LEFTSHIFT = 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'
  • PAGEDOWN = u'\ue00f'_
  • PAGEUP = 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'

7.5. Locate elements By

These are the attributes which can be used to locate elements. Seethe 查找元素 chapter for example usages.

The By implementation.

  • class selenium.webdriver.common.by.By
  • Bases: object

Set of supported locator strategies.

  • CLASSNAME = 'class name'_
  • CSSSELECTOR = 'css selector'_
  • ID = 'id'
  • LINKTEXT = 'link text'_
  • NAME = 'name'
  • PARTIALLINK_TEXT = 'partial link text'_
  • TAGNAME = 'tag name'_
  • XPATH = 'xpath'

7.6. Desired Capabilities

See the 使用远程 Selenium WebDriver section for example usages of desired capabilities.

The Desired Capabilities implementation.

  • class selenium.webdriver.common.desired_capabilities.DesiredCapabilities
  • Bases: object

Set of default supported desired capabilities.

Use this as a starting point for creating a desired capabilities object forrequesting remote webdrivers for connecting to selenium server or selenium grid.

Usage Example:

  1. from selenium import webdriver
  2.  
  3. selenium_grid_url = "http://198.0.0.1:4444/wd/hub"
  4.  
  5. # Create a desired capabilities object as a starting point.
  6. capabilities = DesiredCapabilities.FIREFOX.copy()
  7. capabilities['platform'] = "WINDOWS"
  8. capabilities['version'] = "10"
  9.  
  10. # Instantiate an instance of Remote WebDriver with the desired capabilities.
  11. driver = webdriver.Remote(desired_capabilities=capabilities,
  12. command_executor=selenium_grid_url)

Note: Always use ‘.copy()’ on the DesiredCapabilities object to avoid the sideeffects of altering the Global class instance.

  • ANDROID = {'platform': 'ANDROID', 'browserName': 'android', 'version': ''}
  • CHROME = {'platform': 'ANY', 'browserName': 'chrome', 'version': ''}
  • EDGE = {'platform': 'WINDOWS', 'browserName': 'MicrosoftEdge', 'version': ''}
  • FIREFOX = {'acceptInsecureCerts': True, 'browserName': 'firefox', 'marionette': True}
  • HTMLUNIT = {'platform': 'ANY', 'browserName': 'htmlunit', 'version': ''}
  • HTMLUNITWITHJS = {'platform': 'ANY', 'browserName': 'htmlunit', 'version': 'firefox', 'javascriptEnabled': True}
  • INTERNETEXPLORER = {'platform': 'WINDOWS', 'browserName': 'internet explorer', 'version': ''}
  • IPAD = {'platform': 'MAC', 'browserName': 'iPad', 'version': ''}
  • IPHONE = {'platform': 'MAC', 'browserName': 'iPhone', 'version': ''}
  • OPERA = {'platform': 'ANY', 'browserName': 'opera', 'version': ''}
  • PHANTOMJS = {'platform': 'ANY', 'browserName': 'phantomjs', 'version': '', 'javascriptEnabled': True}
  • SAFARI = {'platform': 'MAC', 'browserName': 'safari', 'version': ''}

7.7. Utilities

The Utils methods.

  • selenium.webdriver.common.utils.findconnectable_ip(_host, port=None)
  • Resolve a hostname to an IP, preferring IPv4 addresses.

We prefer IPv4 so that we don’t change behavior from previous IPv4-onlyimplementations, and because some drivers (e.g., FirefoxDriver) do notsupport IPv6 connections.

If the optional port number is provided, only IPs that listen on the givenport are considered.

Args:

  • host - A hostname.
  • port - Optional port number.Returns:
    A single IP address, as a string. If any IPv4 address is found, one isreturned. Otherwise, if any IPv6 address is found, one is returned. Ifneither, then None is returned.
  • selenium.webdriver.common.utils.free_port()
  • Determines a free port using sockets.

  • selenium.webdriver.common.utils.isconnectable(_port, host='localhost')

  • Tries to connect to the server at port to see if it is running.

Args:

  • port - The port to connect.
  • selenium.webdriver.common.utils.isurl_connectable(_port)
  • Tries to connect to the HTTP server at /status pathand specified port to see if it responds successfully.

Args:

  • port - The port to connect.
  • selenium.webdriver.common.utils.joinhost_port(_host, port)
  • Joins a hostname and port together.

This is a minimal implementation intended to cope with IPv6 literals. Forexample, _join_host_port(‘::1’, 80) == ‘[::1]:80’.

Args:

  • host - A hostname.
  • port - An integer port.
  • selenium.webdriver.common.utils.keysto_typing(_value)
  • Processes the values that will be typed in the element.

7.8. Firefox WebDriver

  • class selenium.webdriver.firefox.webdriver.WebDriver(firefox_profile=None, firefox_binary=None, timeout=30, capabilities=None, proxy=None, executable_path='geckodriver', firefox_options=None, log_path='geckodriver.log')
  • Bases: selenium.webdriver.remote.webdriver.WebDriver

    • context(*args, **kwds)
    • Sets the context that Selenium commands are running in usinga with statement. The state of the context on the server issaved before entering the block, and restored upon exiting it.

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

Usage example:

  1. with selenium.context(selenium.CONTEXT_CHROME):
  2. # chrome scope
  3. ... do stuff ...
  • installaddon(_path, temporary=None)
  • Installs Firefox addon.

Returns identifier of installed addon. This identifier can laterbe used to uninstall addon.

Parameters:path – Absolute path to the addon that will be installed.Usage:driver.install_addon(‘/path/to/firebug.xpi’)

  • quit()
  • Quits the driver and close every associated window.

  • setcontext(_context)

  • uninstalladdon(_identifier)
  • Uninstalls Firefox addon using its identifier.

Usage:driver.uninstall_addon('addon@foo.com‘)

  • CONTEXTCHROME = 'chrome'_
  • CONTEXTCONTENT = 'content'_
  • NATIVEEVENTS_ALLOWED = True_
  • firefox_profile

7.9. 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 fromhttp://chromedriver.storage.googleapis.com/index.html

  • create_options()
  • get_network_conditions()
  • Gets Chrome network emulation settings.

Returns:
A dict. For example:

{‘latency’: 4, ‘download_throughput’: 2, ‘upload_throughput’: 2,‘offline’: False}

  • launchapp(_id)
  • Launches Chrome app specified by id.

  • quit()

  • Closes the browser and shuts down the ChromeDriver executablethat is started when starting the ChromeDriver

  • setnetwork_conditions(**networkconditions)

  • Sets Chrome network emulation settings.

Args:

  1. - network_conditions: A dict with conditions specification.Usage:
  2. - driver.set_network_conditions(
  3. -

offline=False,latency=5, # additional latency (ms)download_throughput=500 1024, # maximal throughputupload_throughput=500 1024) # maximal throughput

Note: ‘throughput’ can be used to set both (for download and upload).

7.10. 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, keep_alive=False, file_detector=None)
  • Bases: object

Controls a browser by sending commands to a remote server.This server is expected to be running the WebDriver wire protocolas defined athttps://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol

Attributes:

  • session_id - String ID of the browser session started and controlled by this WebDriver.
  • command_executor - remote_connection.RemoteConnection object used to execute commands.
  • error_handler - errorhandler.ErrorHandler object used to handle errors.

  • addcookie(_cookie_dict)

  • Adds a cookie to your current session.

Args:

  1. -
  2. - cookie_dict: A dictionary object, with required keys - name and value”;
  3. - optional keys - path”, domain”, secure”, expiry
  4. - Usage:
  5. - 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()

  • createweb_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()

  • deletecookie(_name)
  • 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:

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

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

  • executeasync_script(_script, *args)
  • Asynchronously Executes JavaScript in the current window/frame.

Args:

  1. - script: The JavaScript to execute.
  2. - *args: Any applicable arguments for your JavaScript.Usage:

driver.execute_async_script(‘document.title’)

  • executescript(_script, *args)
  • Synchronously Executes JavaScript in the current window/frame.

Args:

  1. - script: The JavaScript to execute.
  2. - *args: Any applicable arguments for your JavaScript.Usage:

driver.execute_script(‘document.title’)

  • filedetector_context(args, *kwds_)
  • Overrides the current file detector (if necessary) in limited context.Ensures the original file detector is set afterwards.

Example:

  1. - with webdriver.file_detector_context(UselessFileDetector):
  2. - someinput.send_keys(‘/etc/hosts’)

Args:

  1. -
  2. - file_detector_class - Class of the desired file detector. If the class is different
  3. - from the current file_detector, then the class is instantiated with args and kwargsand used as a file detector during the duration of the context manager.
  4. -
  5. - args - Optional arguments that get passed to the file detector class during
  6. - instantiation.
  7. - kwargs - Keyword arguments, passed the same way as args.
  • findelement(_by='id', value=None)
  • ‘Private’ method used by the findelement_by* methods.

Usage:Use the corresponding findelement_by* instead of this.Return type:WebElement

  • findelement_by_class_name(_name)
  • Finds an element by class name.

Args:

  1. - name: The class name of the element to find.Usage:

driver.find_element_by_class_name(‘foo’)

  • findelement_by_css_selector(_css_selector)
  • Finds an element by css selector.

Args:

  1. - css_selector: The css selector to use when finding elements.Usage:

driver.find_element_by_css_selector(‘#foo’)

  • findelementby_id(_id)
  • Finds an element by id.

Args:

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

driver.find_element_by_id(‘foo’)

  • findelement_by_link_text(_link_text)
  • Finds an element by link text.

Args:

  1. - link_text: The text of the element to be found.Usage:

driver.find_element_by_link_text(‘Sign In’)

  • findelement_by_name(_name)
  • Finds an element by name.

Args:

  1. - name: The name of the element to find.Usage:

driver.find_element_by_name(‘foo’)

  • findelement_by_partial_link_text(_link_text)
  • Finds an element by a partial match of its link text.

Args:

  1. - link_text: The text of the element to partially match on.Usage:

driver.find_element_by_partial_link_text(‘Sign’)

  • findelement_by_tag_name(_name)
  • Finds an element by tag name.

Args:

  1. - name: The tag name of the element to find.Usage:

driver.find_element_by_tag_name(‘foo’)

  • findelement_by_xpath(_xpath)
  • Finds an element by xpath.

Args:

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

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

  • findelements(_by='id', value=None)
  • ‘Private’ method used by the findelements_by* methods.

Usage:Use the corresponding findelements_by* instead of this.Return type:list of WebElement

  • findelements_by_class_name(_name)
  • Finds elements by class name.

Args:

  1. - name: The class name of the elements to find.Usage:

driver.find_elements_by_class_name(‘foo’)

  • findelements_by_css_selector(_css_selector)
  • Finds elements by css selector.

Args:

  1. - css_selector: The css selector to use when finding elements.Usage:

driver.find_elements_by_css_selector(‘.foo’)

  • findelementsby_id(_id)
  • Finds multiple elements by id.

Args:

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

driver.find_elements_by_id(‘foo’)

  • findelements_by_link_text(_text)
  • Finds elements by link text.

Args:

  1. - link_text: The text of the elements to be found.Usage:

driver.find_elements_by_link_text(‘Sign In’)

  • findelements_by_name(_name)
  • Finds elements by name.

Args:

  1. - name: The name of the elements to find.Usage:

driver.find_elements_by_name(‘foo’)

  • findelements_by_partial_link_text(_link_text)
  • Finds elements by a partial match of their link text.

Args:

  1. - link_text: The text of the element to partial match on.Usage:

driver.find_element_by_partial_link_text(‘Sign’)

  • findelements_by_tag_name(_name)
  • Finds elements by tag name.

Args:

  1. - name: The tag name the use when finding elements.Usage:

driver.find_elements_by_tag_name(‘foo’)

  • findelements_by_xpath(_xpath)
  • Finds multiple elements by xpath.

Args:

  1. - 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()

  • fullscreen_window()
  • Invokes the window manager-specific ‘full screen’ operation

  • get(url)

  • Loads a web page in the current browser session.

  • getcookie(_name)

  • 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()

  • getlog(_log_type)
  • Gets the log for a given log type

Args:

  1. - log_type: type of log that which will be returnedUsage:

driver.get_log(‘browser’)driver.get_log(‘driver’)driver.get_log(‘client’)driver.get_log(‘server’)

  • 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()
  • getscreenshot_as_file(_filename)

    • Saves a screenshot of the current window to a PNG image file. Returns
    • False if there is any IOError, else returns True. Use full paths inyour filename.
      Args:
    • filename: The full path you wish to save your screenshot to. Thisshould end with a .png extension.Usage:
      driver.get_screenshot_as_file(‘/Screenshots/foo.png’)
  • get_screenshot_as_png()
  • Gets the screenshot of the current window as a binary data.

Usage:driver.get_screenshot_as_png()

  • getwindow_position(_windowHandle='current')
  • Gets the x,y position of the current window.

Usage:driver.get_window_position()

  • get_window_rect()
  • Gets the x, y coordinates of the window as well as height and width ofthe current window.

Usage:driver.get_window_rect()

  • getwindow_size(_windowHandle='current')
  • Gets the width and height of the current window.

Usage:driver.get_window_size()

  • implicitlywait(_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 onetime per session. To set the timeout for calls toexecute_async_script, see set_script_timeout.
      Args:
    • time_to_wait: Amount of time to wait (in seconds)Usage:
      driver.implicitly_wait(30)
  • maximize_window()
  • Maximizes the current window that webdriver is using

  • minimize_window()

  • Invokes the window manager-specific ‘minimize’ operation

  • quit()

  • Quits the driver and closes every associated window.

Usage:driver.quit()

  • refresh()
  • Refreshes the current page.

Usage:driver.refresh()

  • savescreenshot(_filename)
    • Saves a screenshot of the current window to a PNG image file. Returns
    • False if there is any IOError, else returns True. Use full paths inyour filename.
      Args:
    • filename: The full path you wish to save your screenshot to. Thisshould end with a .png extension.Usage:
      driver.save_screenshot(‘/Screenshots/foo.png’)
  • setpage_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 waitUsage:
      driver.set_page_load_timeout(30)
  • setscript_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)
  • setwindow_position(_x, y, windowHandle='current')
  • Sets the x,y position of the current window. (window.moveTo)

Args:

  1. - x: the x-coordinate in pixels to set the window position
  2. - y: the y-coordinate in pixels to set the window positionUsage:

driver.set_window_position(0,0)

  • setwindow_rect(_x=None, y=None, width=None, height=None)
  • Sets the x, y coordinates of the window as well as height and width ofthe current window.

Usage:driver.set_window_rect(x=10, y=10)driver.set_window_rect(width=100, height=200)driver.set_window_rect(x=10, y=10, width=100, height=200)

  • setwindow_size(_width, height, windowHandle='current')
  • Sets the width and height of the current window. (window.resizeTo)

Args:

  1. - width: the width in pixels to set the window to
  2. - height: the height in pixels to set the window toUsage:

driver.set_window_size(800,600)

  • start_client()
  • Called before starting a new session. This method may be overriddento define custom startup behavior.

  • startsession(_capabilities, browser_profile=None)

  • Creates a new session with the desired capabilities.

Args:

  1. - browser_name - The name of the browser to request.
  2. - version - Which browser version to request.
  3. - platform - Which platform to request the browser on.
  4. - javascript_enabled - Whether the new session should support JavaScript.
  5. - 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 overriddento define custom shutdown behavior.

  • switch_to_active_element()

  • Deprecated use driver.switch_to.active_element

  • switch_to_alert()

  • Deprecated use driver.switch_to.alert

  • switch_to_default_content()

  • Deprecated use driver.switch_to.default_content

  • switchto_frame(_frame_reference)

  • Deprecated use driver.switch_to.frame

  • switchto_window(_window_name)

  • Deprecated use driver.switch_to.window

  • 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

  • file_detector

  • log_types
  • Gets a list of the available log types

Usage:driver.log_types

  • mobile
  • name
  • Returns the name of the underlying browser for this instance.

Usage:

  1. - 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

  • switch_to
  • 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

7.11. WebElement

  • class selenium.webdriver.remote.webelement.WebElement(parent, id__, _w3c=False)
  • Bases: object

Represents a DOM element.

Generally, all interesting operations that interact with a document will beperformed through this interface.

All method calls will do a freshness check to ensure that the elementreference is still valid. This essentially determines whether or not theelement is still attached to the DOM. If this test fails, then anStaleElementReferenceException is thrown, and all future calls to thisinstance will fail.

  • clear()
  • Clears the text if it’s a text entry element.

  • click()

  • Clicks the element.

  • findelement(_by='id', value=None)

  • findelement_by_class_name(_name)
  • Finds element within this element’s children by class name.

Args:

  1. - name - class name to search for.
  • findelement_by_css_selector(_css_selector)
  • Finds element within this element’s children by CSS selector.

Args:

  1. - css_selector - CSS selctor string, ex: a.nav#home’
  • findelementby_id(_id)
  • Finds element within this element’s children by ID.

Args:

  1. - id_ - ID of child element to locate.
  • findelement_by_link_text(_link_text)
  • Finds element within this element’s children by visible link text.

Args:

  1. - link_text - Link text string to search for.
  • findelement_by_name(_name)
  • Finds element within this element’s children by name.

Args:

  1. - name - name property of the element to find.
  • findelement_by_partial_link_text(_link_text)
  • Finds element within this element’s children by partially visible link text.

Args:

  1. - link_text - Link text string to search for.
  • findelement_by_tag_name(_name)
  • Finds element within this element’s children by tag name.

Args:

  1. - name - name of html tag (eg: h1, a, span)
  • findelement_by_xpath(_xpath)
  • Finds element by xpath.

Args:xpath - xpath of element to locate. “//input[@class=’myelement’]”

Note: The base path will be relative to this element’s location.

This will select the first link under this element.

  1. myelement.find_elements_by_xpath(".//a")

However, this will select the first link on the page.

  1. myelement.find_elements_by_xpath("//a")
  • findelements(_by='id', value=None)
  • findelements_by_class_name(_name)
  • Finds a list of elements within this element’s children by class name.

Args:

  1. - name - class name to search for.
  • findelements_by_css_selector(_css_selector)
  • Finds a list of elements within this element’s children by CSS selector.

Args:

  1. - css_selector - CSS selctor string, ex: a.nav#home’
  • findelementsby_id(_id)
  • Finds a list of elements within this element’s children by ID.

Args:

  1. - id_ - Id of child element to find.
  • findelements_by_link_text(_link_text)
  • Finds a list of elements within this element’s children by visible link text.

Args:

  1. - link_text - Link text string to search for.
  • findelements_by_name(_name)
  • Finds a list of elements within this element’s children by name.

Args:

  1. - name - name property to search for.
  • findelements_by_partial_link_text(_link_text)
  • Finds a list of elements within this element’s children by link text.

Args:

  1. - link_text - Link text string to search for.
  • findelements_by_tag_name(_name)
  • Finds a list of elements within this element’s children by tag name.

Args:

  1. - name - name of html tag (eg: h1, a, span)
  • findelements_by_xpath(_xpath)
  • Finds elements within the element by xpath.

Args:

  1. - xpath - xpath locator string.

Note: The base path will be relative to this element’s location.

This will select all links under this element.

  1. myelement.find_elements_by_xpath(".//a")

However, this will select all links in the page itself.

  1. myelement.find_elements_by_xpath("//a")
  • getattribute(_name)
  • Gets the given attribute or property of the element.

This method will first try to return the value of a property with thegiven name. If a property with that name doesn’t exist, it returns thevalue of the attribute with the same name. If there’s no attribute withthat name, None is returned.

Values which are considered truthy, that is equals “true” or “false”,are returned as booleans. All other non-None values are returnedas strings. For attributes or properties which do not exist, Noneis returned.

Args:

  1. - name - Name of the attribute/property to retrieve.

Example:

  1. # Check if the "active" CSS class is applied to an element.
  2. is_active = "active" in target_element.get_attribute("class")
  • getproperty(_name)
  • Gets the given property of the element.

Args:

  1. - name - Name of the property to retrieve.

Example:

  1. # Check if the "active" CSS class is applied to an element.
  2. text_length = target_element.get_property("text_length")
  • is_displayed()
  • Whether the element is visible to a user.

  • is_enabled()

  • Returns whether the element is enabled.

  • is_selected()

  • Returns whether the element is selected.

Can be used to check if a checkbox or radio button is selected.

  • screenshot(filename)
    • Saves a screenshot of the current element to a PNG image file. Returns
    • False if there is any IOError, else returns True. Use full paths inyour filename.
      Args:
    • filename: The full path you wish to save your screenshot to. Thisshould end with a .png extension.Usage:
      element.screenshot(‘/Screenshots/foo.png’)
  • sendkeys(*value_)
  • Simulates typing into the element.

Args:

  1. - value - A string for typing, or setting form fields. For settingfile inputs, this could be a local file path.

Use this to send simple key events or to fill out form fields:

  1. form_textfield = driver.find_element_by_name('username')
  2. form_textfield.send_keys("admin")

This can also be used to set file inputs.

  1. file_input = driver.find_element_by_name('profilePic')
  2. file_input.send_keys("path/to/profilepic.gif")
  3. # Generally it's better to wrap the file path in one of the methods
  4. # in os.path to return the actual path to support cross OS testing.
  5. # file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))
  • submit()
  • Submits a form.

  • valueof_css_property(_property_name)

  • The value of a CSS property.

  • id

  • Internal ID used by selenium.

This is mainly for internal use. Simple use cases such as checking if 2webelements refer to the same element, can be done using ==:

  1. if element1 == element2:
  2. print("These 2 are equal")
  • location
  • The location of the element in the renderable canvas.

  • location_once_scrolled_into_view

  • THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discoverwhere on the screen an element is so that we can click it. This methodshould cause the element to be scrolled into view.

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

  • parent
  • Internal reference to the WebDriver instance this element was found from.

  • rect

  • A dictionary with the size and location of the element.

  • screenshot_as_base64

  • Gets the screenshot of the current element as a base64 encoded string.

Usage:img_b64 = element.screenshot_as_base64

  • screenshot_as_png
  • Gets the screenshot of the current element as a binary data.

Usage:element_png = element.screenshot_as_png

  • size
  • The size of the element.

  • tag_name

  • This element’s tagName property.

  • text

  • The text of the element.

7.12. UI Support

  • class selenium.webdriver.support.select.Select(webelement)
  • Bases: object

    • deselect_all()
    • Clear all selected entries. This is only valid when the SELECT supports multiple selections.throws NotImplementedError If the SELECT does not support multiple selections

    • deselectby_index(_index)

    • Deselect the option at the given index. This is done by examing the “index” attribute of anelement, and not merely by counting.

Args:

  1. - index - The option at this index will be deselected

throws NoSuchElementException If there is no option with specisied index in SELECT

  • deselectby_value(_value)
  • Deselect all options that have a value matching the argument. That is, when given “foo” thiswould deselect an option like:

Args:

  1. - value - The value to match against

throws NoSuchElementException If there is no option with specisied value in SELECT

  • deselectby_visible_text(_text)
  • Deselect all options that display text matching the argument. That is, when given “Bar” thiswould deselect an option like:

Args:

  1. - text - The visible text to match against
  • selectby_index(_index)
  • Select the option at the given index. This is done by examing the “index” attribute of anelement, and not merely by counting.

Args:

  1. - index - The option at this index will be selected

throws NoSuchElementException If there is no option with specisied index in SELECT

  • selectby_value(_value)
  • Select all options that have a value matching the argument. That is, when given “foo” thiswould select an option like:

Args:

  1. - value - The value to match against

throws NoSuchElementException If there is no option with specisied value in SELECT

  • selectby_visible_text(_text)
  • Select all options that display text matching the argument. That is, when given “Bar” thiswould select an option like:

Args:

  1. - text - The visible text to match against

throws NoSuchElementException If there is no option with specisied text in SELECT

  • all_selected_options
  • Returns a list of all selected options belonging to this select tag

  • first_selected_option

  • The first selected option in this select tag (or the currently selected option in anormal select)

  • options

  • Returns a list of all options belonging to this select tag
  • class selenium.webdriver.support.wait.WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None)
  • Bases: object

    • until(method, message='')
    • Calls the method provided with the driver as an argument until the return value is not False.

    • untilnot(_method, message='')

    • Calls the method provided with the driver as an argument until the return value is False.

7.13. Color Support

  • class selenium.webdriver.support.color.Color(red, green, blue, alpha=1)
  • Bases: object

Color conversion support class

Example:

  1. from selenium.webdriver.support.color import Color
  2.  
  3. print(Color.from_string('#00ff33').rgba)
  4. print(Color.from_string('rgb(1, 255, 3)').hex)
  5. print(Color.from_string('blue').rgba)
  • static fromstring(str)
  • hex
  • rgb
  • rgba

7.14. Expected conditions Support

  • class selenium.webdriver.support.expected_conditions.alert_is_present
  • Bases: object

Expect an alert to be present.

  • class selenium.webdriver.support.expectedconditions.element_located_selection_state_to_be(_locator, is_selected)
  • Bases: object

An expectation to locate an element and check if the selection statespecified is in that state.locator is a tuple of (by, path)is_selected is a boolean

  • class selenium.webdriver.support.expectedconditions.element_located_to_be_selected(_locator)
  • Bases: object

An expectation for the element to be located is selected.locator is a tuple of (by, path)

  • class selenium.webdriver.support.expectedconditions.element_selection_state_to_be(_element, is_selected)
  • Bases: object

An expectation for checking if the given element is selected.element is WebElement objectis_selected is a Boolean.”

  • class selenium.webdriver.support.expectedconditions.element_to_be_clickable(_locator)
  • Bases: object

An Expectation for checking an element is visible and enabled such thatyou can click it.

  • class selenium.webdriver.support.expectedconditions.element_to_be_selected(_element)
  • Bases: object

An expectation for checking the selection is selected.element is WebElement object

  • class selenium.webdriver.support.expectedconditions.frame_to_be_available_and_switch_to_it(_locator)
  • Bases: object

An expectation for checking whether the given frame is available toswitch to. If the frame is available it switches the given driver to thespecified frame.

  • class selenium.webdriver.support.expectedconditions.invisibility_of_element_located(_locator)
  • Bases: object

An Expectation for checking that an element is either invisible or notpresent on the DOM.

locator used to find the element

  • class selenium.webdriver.support.expectedconditions.new_window_is_opened(_current_handles)
  • Bases: object

An expectation that a new window will be opened and have the number ofwindows handles increase

  • class selenium.webdriver.support.expectedconditions.number_of_windows_to_be(_num_windows)
  • Bases: object

An expectation for the number of windows to be a certain value.

  • class selenium.webdriver.support.expectedconditions.presence_of_all_elements_located(_locator)
  • Bases: object

An expectation for checking that there is at least one element presenton a web page.locator is used to find the elementreturns the list of WebElements once they are located

  • class selenium.webdriver.support.expectedconditions.presence_of_element_located(_locator)
  • Bases: object

An expectation for checking that an element is present on the DOMof a page. This does not necessarily mean that the element is visible.locator - used to find the elementreturns the WebElement once it is located

  • class selenium.webdriver.support.expectedconditions.staleness_of(_element)
  • Bases: object

Wait until an element is no longer attached to the DOM.element is the element to wait for.returns False if the element is still attached to the DOM, true otherwise.

  • class selenium.webdriver.support.expectedconditions.text_to_be_present_in_element(_locator, text_)
  • Bases: object

An expectation for checking if the given text is present in thespecified element.locator, text

  • class selenium.webdriver.support.expectedconditions.text_to_be_present_in_element_value(_locator, text_)
  • Bases: object

An expectation for checking if the given text is present in the element’slocator, text

  • class selenium.webdriver.support.expectedconditions.title_contains(_title)
  • Bases: object

An expectation for checking that the title contains a case-sensitivesubstring. title is the fragment of title expectedreturns True when the title matches, False otherwise

  • class selenium.webdriver.support.expectedconditions.title_is(_title)
  • Bases: object

An expectation for checking the title of a page.title is the expected title, which must be an exact matchreturns True if the title matches, false otherwise.

  • class selenium.webdriver.support.expectedconditions.url_changes(_url)
  • Bases: object

An expectation for checking the current url.url is the expected url, which must not be an exact matchreturns True if the url is different, false otherwise.

  • class selenium.webdriver.support.expectedconditions.url_contains(_url)
  • Bases: object

An expectation for checking that the current url contains acase-sensitive substring.url is the fragment of url expected,returns True when the title matches, False otherwise

  • class selenium.webdriver.support.expectedconditions.url_matches(_pattern)
  • Bases: object

An expectation for checking the current url.pattern is the expected pattern, which must be an exact matchreturns True if the title matches, false otherwise.

  • class selenium.webdriver.support.expectedconditions.url_to_be(_url)
  • Bases: object

An expectation for checking the current url.url is the expected url, which must be an exact matchreturns True if the title matches, false otherwise.

  • class selenium.webdriver.support.expectedconditions.visibility_of(_element)
  • Bases: object

An expectation for checking that an element, known to be present on theDOM of a page, is visible. Visibility means that the element is not onlydisplayed but also has a height and width that is greater than 0.element is the WebElementreturns the (same) WebElement once it is visible

  • class selenium.webdriver.support.expectedconditions.visibility_of_all_elements_located(_locator)
  • Bases: object

An expectation for checking that all elements are present on the DOM of apage and visible. Visibility means that the elements are not only displayedbut also has a height and width that is greater than 0.locator - used to find the elementsreturns the list of WebElements once they are located and visible

  • class selenium.webdriver.support.expectedconditions.visibility_of_any_elements_located(_locator)
  • Bases: object

An expectation for checking that there is at least one element visibleon a web page.locator is used to find the elementreturns the list of WebElements once they are located

  • class selenium.webdriver.support.expectedconditions.visibility_of_element_located(_locator)
  • Bases: object

An expectation for checking that an element is present on the DOM of apage and visible. Visibility means that the element is not only displayedbut also has a height and width that is greater than 0.locator - used to find the elementreturns the WebElement once it is located and visible