webdriver package

Subpackages

Submodules

webdriver.appium_connection module

class AppiumConnection(remote_server_addr, keep_alive=False, resolve_ip=None, ignore_proxy=False)

Bases: selenium.webdriver.remote.remote_connection.RemoteConnection

classmethod get_remote_connection_headers(parsed_url: ParseResult, keep_alive: bool = True) Dict[str, Any]

Override get_remote_connection_headers in RemoteConnection

webdriver.appium_service module

class AppiumService

Bases: object

property is_listening: bool

Check if the service is listening on the given/default host/port.

The fact, that the service is running, does not always mean it is listening. the default host/port values can be customized by providing –address/–port command line arguments while starting the service.

Returns

True if the service is running and listening on the given/default host/port

Return type

bool

property is_running: bool

Check if the service is running.

Returns

True if the service is running

Return type

bool

start(**kwargs: Any) subprocess.Popen

Starts Appium service with given arguments.

The service will be forcefully restarted if it is already running.

Keyword Arguments
  • env (dict) – Environment variables mapping. The default system environment, which is inherited from the parent process, is assigned by default.

  • node (str) – The full path to the main NodeJS executable. The service will try to retrieve it automatically by default.

  • stdout (int) – Check the documentation for subprocess.Popen for more details. The default value is subprocess.DEVNULL on Windows and subprocess.PIPE on other platforms.

  • stderr (int) – Check the documentation for subprocess.Popen for more details. The default value is subprocess.DEVNULL on Windows and subprocess.PIPE on other platforms.

  • timeout_ms (int) – The maximum time to wait until Appium process starts listening for HTTP connections. If set to zero or a negative number then no wait will be applied. 60000 ms by default.

  • main_script (str) – The full path to the main Appium executable (usually located at build/lib/main.js). If this is not set then the service tries to detect the path automatically.

  • args (str) – List of Appium arguments (all must be strings). Check https://appium.io/docs/en/writing-running-appium/server-args/ for more details about possible arguments and their values.

Returns

You can use Popen.communicate interface or stderr/stdout properties of the instance (stdout/stderr must not be set to None in such case) in order to retrieve the actual process output.

stop() bool

Stops Appium service if it is running.

The call will be ignored if the service is not running or has been already stopped.

Returns

True if the service was running before being stopped

exception AppiumServiceError

Bases: RuntimeError

find_executable(executable: str) Optional[str]
poll_url(host: str, port: int, path: str, timeout_ms: int) bool

webdriver.applicationstate module

class ApplicationState

Bases: object

NOT_INSTALLED = 0
NOT_RUNNING = 1
RUNNING_IN_BACKGROUND = 3
RUNNING_IN_BACKGROUND_SUSPENDED = 2
RUNNING_IN_FOREGROUND = 4

webdriver.clipboard_content_type module

class ClipboardContentType

Bases: object

IMAGE = 'image'
PLAINTEXT = 'plaintext'
URL = 'url'

webdriver.command_method module

class CommandMethod(value)

Bases: enum.Enum

An enumeration.

CONNECT = 'CONNECT'
DELETE = 'DELETE'
GET = 'GET'
HEAD = 'HEAD'
OPTIONS = 'OPTIONS'
PATCH = 'PATCH'
POST = 'POST'
PUT = 'PUT'
TRACE = 'TRACE'

webdriver.connectiontype module

Connection types are specified here:

https://code.google.com/p/selenium/source/browse/spec-draft.md?repo=mobile#120

Value (Alias)

Data

Wifi

Airplane Mode

0 (None)

0

0

0

1 (Airplane Mode)

0

0

1

2 (Wifi only)

0

1

0

4 (Data only)

1

0

0

6 (All network on)

1

1

0

class ConnectionType

Bases: object

AIRPLANE_MODE = 1
ALL_NETWORK_ON = 6
DATA_ONLY = 4
NO_CONNECTION = 0
WIFI_ONLY = 2

webdriver.errorhandler module

class MobileErrorHandler

Bases: selenium.webdriver.remote.errorhandler.ErrorHandler

check_response(response: Dict) None

Checks that a JSON response from the WebDriver does not have an error.

Args
  • response - The JSON response from the WebDriver server as a dictionary object.

Raises

If the response contains an error message.

webdriver.mobilecommand module

class MobileCommand

Bases: object

ACTIVATE_APP = 'activateApp'
ACTIVATE_IME_ENGINE = 'activateIMEEngine'
BACKGROUND = 'background'
CLEAR = 'clear'
CLOSE_APP = 'closeApp'
COMPARE_IMAGES = 'compareImages'
CONTEXTS = 'getContexts'
DEACTIVATE_IME_ENGINE = 'deactivateIMEEngine'
END_TEST_COVERAGE = 'endTestCoverage'
EXECUTE_DRIVER = 'executeDriver'
FINGER_PRINT = 'fingerPrint'
GET_ACTIVE_IME_ENGINE = 'getActiveEngine'
GET_ALL_SESSIONS = 'getAllSessions'
GET_APP_STRINGS = 'getAppStrings'
GET_AVAILABLE_IME_ENGINES = 'getAvailableIMEEngines'
GET_AVAILABLE_LOG_TYPES = 'getAvailableLogTypes'
GET_CLIPBOARD = 'getClipboard'
GET_CURRENT_ACTIVITY = 'getCurrentActivity'
GET_CURRENT_CONTEXT = 'getCurrentContext'
GET_CURRENT_PACKAGE = 'getCurrentPackage'
GET_DEVICE_TIME_GET = 'getDeviceTimeGet'
GET_DEVICE_TIME_POST = 'getDeviceTimePost'
GET_DISPLAY_DENSITY = 'getDisplayDensity'
GET_EVENTS = 'getLogEvents'
GET_LOCATION = 'getLocation'
GET_LOG = 'getLog'
GET_NETWORK_CONNECTION = 'getNetworkConnection'
GET_PERFORMANCE_DATA = 'getPerformanceData'
GET_PERFORMANCE_DATA_TYPES = 'getPerformanceDataTypes'
GET_SESSION = 'getSession'
GET_SETTINGS = 'getSettings'
GET_SYSTEM_BARS = 'getSystemBars'
HIDE_KEYBOARD = 'hideKeyboard'
INSTALL_APP = 'installApp'
IS_APP_INSTALLED = 'isAppInstalled'
IS_IME_ACTIVE = 'isIMEActive'
IS_KEYBOARD_SHOWN = 'isKeyboardShown'
IS_LOCKED = 'isLocked'
KEY_EVENT = 'keyEvent'
LAUNCH_APP = 'launchApp'
LOCATION_IN_VIEW = 'locationInView'
LOCK = 'lock'
LOG_EVENT = 'logCustomEvent'
LONG_PRESS_KEYCODE = 'longPressKeyCode'
MAKE_GSM_CALL = 'makeGsmCall'
MULTI_ACTION = 'multiAction'
OPEN_NOTIFICATIONS = 'openNotifications'
PRESS_KEYCODE = 'pressKeyCode'
PULL_FILE = 'pullFile'
PULL_FOLDER = 'pullFolder'
PUSH_FILE = 'pushFile'
QUERY_APP_STATE = 'queryAppState'
REMOVE_APP = 'removeApp'
REPLACE_KEYS = 'replaceKeys'
RESET = 'reset'
SEND_SMS = 'sendSms'
SET_CLIPBOARD = 'setClipboard'
SET_GSM_SIGNAL = 'setGsmSignal'
SET_GSM_VOICE = 'setGsmVoice'
SET_IMMEDIATE_VALUE = 'setImmediateValue'
SET_LOCATION = 'setLocation'
SET_NETWORK_CONNECTION = 'setNetworkConnection'
SET_NETWORK_SPEED = 'setNetworkSpeed'
SET_POWER_AC = 'setPowerAc'
SET_POWER_CAPACITY = 'setPowerCapacity'
SHAKE = 'shake'
START_ACTIVITY = 'startActivity'
START_RECORDING_SCREEN = 'startRecordingScreen'
STOP_RECORDING_SCREEN = 'stopRecordingScreen'
SWITCH_TO_CONTEXT = 'switchToContext'
TERMINATE_APP = 'terminateApp'
TOGGLE_LOCATION_SERVICES = 'toggleLocationServices'
TOGGLE_TOUCH_ID_ENROLLMENT = 'toggleTouchIdEnrollment'
TOGGLE_WIFI = 'toggleWiFi'
TOUCH_ACTION = 'touchAction'
TOUCH_ID = 'touchId'
UNLOCK = 'unlock'
UPDATE_SETTINGS = 'updateSettings'

webdriver.switch_to module

class MobileSwitchTo(driver)

Bases: selenium.webdriver.remote.switch_to.SwitchTo

context(context_name: Optional[str]) WebDriver

Sets the context for the current session. Passing None is equal to switching to native context.

Parameters

context_name – The name of the context to switch to.

Usage:

driver.switch_to.context(‘WEBVIEW_1’)

webdriver.webdriver module

class ExtensionBase(execute: Callable[[str, Dict], Dict[str, Any]])

Bases: object

Used to define an extension command as driver’s methods.

Example

When you want to add example_command which calls a get request to session/$sessionId/path/to/your/custom/url.

  1. Defines an extension as a subclass of ExtensionBase
    class YourCustomCommand(ExtensionBase):
    def method_name(self):

    return ‘custom_method_name’

    # Define a method with the name of method_name def custom_method_name(self):

    # Generally the response of Appium follows { ‘value’: { data } } # format. return self.execute()[‘value’]

    # Used to register the command pair as “Appium command” in this driver. def add_command(self):

    return (‘GET’, ‘session/$sessionId/path/to/your/custom/url’)

  2. Creates a session with the extension.

    # Appium capabilities desired_caps = { … } driver = webdriver.Remote(’http://localhost:4723/wd/hub’, desired_caps,

    extensions=[YourCustomCommand])

  3. Calls the custom command

    # Then, the driver calls a get request against # session/$sessionId/path/to/your/custom/url. $sessionId will be # replaced properly in the driver. Then, the method returns # the value part of the response. driver.custom_method_name()

  4. Remove added commands (if needed)

    # New commands are added by setattr. They remain in the module, # so you should explicitly delete them to define the same name method # with different arguments or process in the method. driver.delete_extensions()

You can give arbitrary arguments for the command like the below.

class YourCustomCommand(ExtensionBase):
def method_name(self):

return ‘custom_method_name’

def test_command(self, argument):

return self.execute(argument)[‘value’]

def add_command(self):

return (‘post’, ‘session/$sessionId/path/to/your/custom/url’)

driver = webdriver.Remote(’http://localhost:4723/wd/hub’, desired_caps,

extensions=[YourCustomCommand])

# Then, the driver sends a post request to session/$sessionId/path/to/your/custom/url # with {‘dummy_arg’: ‘as a value’} JSON body. driver.custom_method_name({‘dummy_arg’: ‘as a value’})

When you customize the URL dinamically with element id.

class CustomURLCommand(ExtensionBase):
def method_name(self):

return ‘custom_method_name’

def custom_method_name(self, element_id):

return self.execute({‘id’: element_id})[‘value’]

def add_command(self):

return (‘GET’, ‘session/$sessionId/path/to/your/custom/$id/url’)

driver = webdriver.Remote(’http://localhost:4723/wd/hub’, desired_caps,

extensions=[YourCustomCommand])

element = driver.find_elemeent(by=AppiumBy.ACCESSIBILITY_ID, value=’id’)

# Then, the driver calls a get request to session/$sessionId/path/to/your/custom/$id/url # with replacing the $id with the given element.id driver.custom_method_name(element.id)

add_command() Tuple[str, str]

Expected to define the pair of HTTP method and its URL.

execute(parameters: Optional[Dict[str, Any]] = None) Any
method_name() str

Expected to return a method name. This name will be available as a driver method.

Returns

‘str’ The method name.

class WebDriver(command_executor: str = 'http://127.0.0.1:4444/wd/hub', desired_capabilities: Optional[Dict] = None, browser_profile: Optional[str] = None, proxy: Optional[str] = None, keep_alive: bool = True, direct_connection: bool = True, extensions: Optional[List[webdriver.webdriver.WebDriver]] = None, strict_ssl: bool = True)

Bases: selenium.webdriver.remote.webdriver.WebDriver, webdriver.extensions.search_context.AppiumSearchContext, webdriver.extensions.action_helpers.ActionHelpers, webdriver.extensions.android.activities.Activities, webdriver.extensions.applications.Applications, webdriver.extensions.clipboard.Clipboard, webdriver.extensions.context.Context, webdriver.extensions.android.common.Common, webdriver.extensions.device_time.DeviceTime, webdriver.extensions.android.display.Display, webdriver.extensions.execute_driver.ExecuteDriver, webdriver.extensions.execute_mobile_command.ExecuteMobileCommand, webdriver.extensions.android.gsm.Gsm, webdriver.extensions.hw_actions.HardwareActions, webdriver.extensions.images_comparison.ImagesComparison, webdriver.extensions.ime.IME, webdriver.extensions.keyboard.Keyboard, webdriver.extensions.location.Location, webdriver.extensions.log_event.LogEvent, webdriver.extensions.android.network.Network, webdriver.extensions.android.performance.Performance, webdriver.extensions.android.power.Power, webdriver.extensions.remote_fs.RemoteFS, webdriver.extensions.screen_record.ScreenRecord, webdriver.extensions.session.Session, webdriver.extensions.settings.Settings, webdriver.extensions.android.sms.Sms, webdriver.extensions.android.system_bars.SystemBars

create_web_element(element_id: Union[int, str]) webdriver.webelement.WebElement

Creates a web element with the specified element_id.

Overrides method in Selenium WebDriver in order to always give them Appium WebElement

Parameters

element_id – The element id to create a web element

Returns

MobileWebElement

delete_extensions() None

Delete extensions added in the class with ‘setattr’

find_element(by: str = 'id', value: Optional[Union[str, Dict]] = None) webdriver.webelement.WebElement

Find an element given a AppiumBy strategy and locator

Parameters
  • by – The strategy

  • value – The locator

Usage:

driver.find_element(by=AppiumBy.ACCESSIBILITY_ID, value=’accessibility_id’)

Returns

The found element

Return type

appium.webdriver.webelement.WebElement

find_elements(by: str = 'id', value: Optional[Union[str, Dict]] = None) Union[List[webdriver.webelement.WebElement], List]

Find elements given a AppiumBy strategy and locator

Parameters
  • by – The strategy

  • value – The locator

Usage:

driver.find_elements(by=AppiumBy.ACCESSIBILITY_ID, value=’accessibility_id’)

Returns

The found elements

Return type

list of appium.webdriver.webelement.WebElement

set_value(element: webdriver.webelement.WebElement, value: str) webdriver.webdriver.WebDriver

Set the value on an element in the application.

Parameters
  • element – the element whose value will be set

  • value – the value to set on the element

Returns

Self instance

Return type

appium.webdriver.webdriver.WebDriver

start_session(capabilities: Dict, browser_profile: Optional[str] = None) None

Creates a new session with the desired capabilities.

Override for Appium

Parameters
  • capabilities – Capabilities which have following keys like ‘automation_name’, ‘platform_name’,

  • 'platform_version'

  • 'app'.

  • https (Read) – //github.com/appium/appium/blob/master/docs/en/writing-running-appium/caps.md for more details.

  • browser_profile – Browser profile

property switch_to: webdriver.switch_to.MobileSwitchTo

Returns an object containing all options to switch focus into

Override for appium

Returns

appium.webdriver.switch_to.MobileSwitchTo

webdriver.webelement module

class WebElement(parent, id_)

Bases: selenium.webdriver.remote.webelement.WebElement, webdriver.extensions.search_context.AppiumWebElementSearchContext

clear() webdriver.webelement.WebElement

Clears text.

Override for Appium

Returns

appium.webdriver.webelement.WebElement

find_element(by: str = 'id', value: Optional[Union[str, Dict]] = None) webdriver.webelement.WebElement

Find an element given a AppiumBy strategy and locator

Override for Appium

Prefer the find_element_by_* methods when possible.

Parameters
  • by – The strategy

  • value – The locator

Usage:

element = element.find_element(AppiumBy.ID, ‘foo’)

Returns

appium.webdriver.webelement.WebElement

find_elements(by: str = 'id', value: Optional[Union[str, Dict]] = None) List[webdriver.webelement.WebElement]

Find elements given a AppiumBy strategy and locator

Parameters
  • by – The strategy

  • value – The locator

Usage:

element = element.find_elements(AppiumBy.CLASS_NAME, ‘foo’)

Returns

list of appium.webdriver.webelement.WebElement

get_attribute(name: str) Optional[Union[str, Dict]]

Gets the given attribute or property of the element.

Override for Appium

This method will first try to return the value of a property with the given name. If a property with that name doesn’t exist, it returns the value of the attribute with the same name. If there’s no attribute with that 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 returned as strings. For attributes or properties which do not exist, None is returned.

Parameters

name – Name of the attribute/property to retrieve.

Usage:

# Check if the “active” CSS class is applied to an element.

is_active = “active” in target_element.get_attribute(“class”)

Returns

The given attribute or property of the element

is_displayed() bool

Whether the element is visible to a user.

Override for Appium

property location_in_view: Dict[str, int]

Gets the location of an element relative to the view.

Usage:
location = element.location_in_view
x = location[‘x’]
y = location[‘y’]
Returns

The location of an element relative to the view

Return type

dict

send_keys(*value: str) webdriver.webelement.WebElement

Simulates typing into the element.

Parameters

value – A string for typing.

Returns

appium.webdriver.webelement.WebElement

set_text(keys: str = '') webdriver.webelement.WebElement

Sends text to the element.

Previous text is removed. Android only.

Parameters

keys – the text to be sent to the element.

Usage:

element.set_text(‘some text’)

Returns

appium.webdriver.webelement.WebElement

set_value(value: str) webdriver.webelement.WebElement

Set the value on this element in the application

Parameters

value – The value to be set

Returns

appium.webdriver.webelement.WebElement

Module contents

Appium Python Client: WebDriver module