webdriver package

Subpackages

Submodules

webdriver.appium_connection module

class AppiumConnection(remote_server_addr: str, keep_alive: bool = False, ignore_proxy: bool | None = False, init_args_for_pool_manager: Dict[str, Any] | None = None)

Bases: 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/base path values can be customized by providing –address/–port/–base-path 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) Popen

Starts Appium service with given arguments.

If you use the service to start Appium 1.x then consider providing [’–base-path’, ‘/wd/hub’] arguments. By default, the service assumes Appium server listens on ‘/’ path, which is the default path for Appium 2.

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 if not provided.

  • npm (str) – The full path to the Node Package Manager (npm) script. The service will try to retrieve it automatically if not provided.

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

exception AppiumStartupError

Bases: RuntimeError

find_executable(executable: str) str | None
get_main_script(node: str | None, npm: str | None) str
get_node() str
get_npm() str
make_status_url(args: List[str]) str
parse_arg_value(args: List[str], arg_names: Set[str], default: str) str
parse_base_path(args: List[str]) str
parse_host(args: List[str]) str
parse_port(args: List[str]) int

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, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

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: ErrorHandler

check_response(response: Dict[str, Any]) None

https://www.w3.org/TR/webdriver/#errors

format_stacktrace(original: None | str | Sequence) List[str]

webdriver.mobilecommand module

class MobileCommand

Bases: object

ACTIVATE_APP = 'activateApp'
BACKGROUND = 'background'
CLEAR = 'clear'
COMPARE_IMAGES = 'compareImages'
CONTEXTS = 'getContexts'
EXECUTE_DRIVER = 'executeDriver'
FINGER_PRINT = 'fingerPrint'
GET_APP_STRINGS = 'getAppStrings'
GET_AVAILABLE_LOG_TYPES = 'getAvailableLogTypes'
GET_CAPABILITIES = 'getCapabilities'
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_SCREEN_ORIENTATION = 'getScreenOrientation'
GET_SESSION = 'getSession'
GET_SETTINGS = 'getSettings'
GET_STATUS = 'getStatus'
GET_SYSTEM_BARS = 'getSystemBars'
HIDE_KEYBOARD = 'hideKeyboard'
INSTALL_APP = 'installApp'
IS_APP_INSTALLED = 'isAppInstalled'
IS_ELEMENT_DISPLAYED = 'isElementDisplayed'
IS_KEYBOARD_SHOWN = 'isKeyboardShown'
IS_LOCKED = 'isLocked'
KEY_EVENT = 'keyEvent'
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'
SEND_SMS = 'sendSms'
SET_CLIPBOARD = 'setClipboard'
SET_GSM_SIGNAL = 'setGsmSignal'
SET_GSM_VOICE = 'setGsmVoice'
SET_LOCATION = 'setLocation'
SET_NETWORK_CONNECTION = 'setNetworkConnection'
SET_NETWORK_SPEED = 'setNetworkSpeed'
SET_POWER_AC = 'setPowerAc'
SET_POWER_CAPACITY = 'setPowerCapacity'
SET_SCREEN_ORIENTATION = 'setScreenOrientation'
SHAKE = 'shake'
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 HasDriver(*args, **kwargs)

Bases: Protocol

class MobileSwitchTo(driver)

Bases: SwitchTo, HasDriver

context(context_name: str | None) 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 options = AppiumOptions() driver = webdriver.Remote(’http://localhost:4723/wd/hub’, options=options,

    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: Dict[str, Any] | None = 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 | AppiumConnection = 'http://127.0.0.1:4444/wd/hub', keep_alive: bool = True, direct_connection: bool = True, extensions: List[WebDriver] | None = None, strict_ssl: bool = True, options: AppiumOptions | List[AppiumOptions] | None = None)

Bases: WebDriver, ActionHelpers, Activities, Applications, Clipboard, Context, Common, DeviceTime, Display, ExecuteDriver, ExecuteMobileCommand, Gsm, HardwareActions, ImagesComparison, Keyboard, Location, LogEvent, Network, Performance, Power, RemoteFS, ScreenRecord, Session, Settings, Sms, SystemBars

assert_extension_exists(ext_name: str) WebDriver

Verifies if the given extension is not present in the list of absent extensions for the given driver instance. This API is designed for private usage.

Parameters:

ext_name – extension name

Returns:

self instance for chaining

Raises:

UnknownMethodException – If the extension has been marked as absent once

create_web_element(element_id: int | str) 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: str | Dict | None = None) 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: str | Dict | None = None) List[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

get_status() Dict

Get the Appium server status

Usage:

driver.get_status()

Returns:

The status information

Return type:

Dict

mark_extension_absence(ext_name: str) WebDriver

Marks the given extension as absent for the given driver instance. This API is designed for private usage.

Parameters:

ext_name – extension name

Returns:

self instance for chaining

property orientation: str

Gets the current orientation of the device :Usage:

::

orientation = driver.orientation

start_session(capabilities: Dict | AppiumOptions, browser_profile: str | None = None) None

Creates a new session with the desired capabilities.

Override for Appium

Parameters:
property 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: WebElement

clear() WebElement

Clears text.

Override for Appium

Returns:

appium.webdriver.webelement.WebElement

find_element(by: str = 'id', value: str | Dict | None = None) 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: str | Dict | None = None) List[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) str | Dict | None

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) WebElement

Simulates typing into the element.

Parameters:

value – A string for typing.

Returns:

appium.webdriver.webelement.WebElement

Module contents

Appium Python Client: WebDriver module