webdriver package#

Subpackages#

Submodules#

webdriver.appium_connection module#

class AppiumConnection(remote_server_addr: str | None = None, keep_alive: bool = True, ignore_proxy: bool = False, ignore_certificates: bool | None = False, init_args_for_pool_manager: dict | None = None, client_config: ClientConfig | None = None)#

Bases: RemoteConnection

A subclass of selenium.webdriver.remote.remote_connection.Remoteconnection.

The changes are

  • The default user agent

  • Adds ‘X-Idempotency-Key’ header in a new session request to avoid proceeding

    the same request multiple times in the Appium server side. * appium/appium-base-driver#400

extra_headers = {}#
classmethod get_remote_connection_headers(parsed_url: ParseResult, keep_alive: bool = True) → dict[str, Any]#

Override get_remote_connection_headers in RemoteConnection to control the extra headers. This method will be used in sending a request method in this class.

user_agent = 'appium/6.6.0 (selenium/4.52.0 (python linux))'#

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

property is_running: bool#

Check if the service is running.

Returns:

True if the service is running

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.

Parameters:
  • 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(timeout: float = 5.5) → bool#

Stops Appium service if it is running.

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

Parameters:

timeout – The maximum time in float seconds to wait for the server process to terminate

Returns:

True if the service was running before being stopped

exception AppiumServiceError#

Bases: RuntimeError

exception AppiumStartupError#

Bases: RuntimeError

get_main_script(node: str | None, npm: str | None) → str#
get_node() → str#
get_npm() → str#
is_service_listening(url: str, timeout: float = 5, custom_validator: Callable[[], None] | None = None) → bool#

Check if the service is running

Parameters:
  • url – Full server url

  • timeout – Timeout in float seconds

  • custom_validator – Custom callable method to be executed upon each validation loop before the timeout happens

Returns:

True if Appium server is running before the timeout

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.client_config module#

class AppiumClientConfig(remote_server_addr: str, *args, **kwargs)#

Bases: ClientConfig

ClientConfig class for Appium Python client. This class inherits selenium.webdriver.remote.client_config.ClientConfig.

property direct_connection: bool#

//github.com/appium/python-client?tab=readme-ov-file#direct-connect-urls) is enabled.

Type:

Return if [directConnect](https

webdriver.clipboard_content_type module#

class ClipboardContentType#

Bases: object

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

webdriver.command_method module#

class CommandMethod(*values)#

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#

Handle W3C and HTTP error responses, retaining Appium-specific exception mappings.

webdriver.locator_converter module#

class AppiumLocatorConverter#

Bases: LocatorConverter

A custom locator converter in Appium.

Appium supports locators which are not defined in W3C WebDriver, so Appium Python client wants to keep the given locators to the Appium server as-is.

convert(by: str, value: str) → tuple[str, str]#

webdriver.switch_to module#

class MobileSwitchTo(driver)#

Bases: SwitchTo

context(context_name: str | None) → Self#

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 custom_method_name(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', options=options,
    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 dynamically 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', options=options,
    extensions=[CustomURLCommand])
element = driver.find_element(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:4723', extensions: list[type[ExtensionBase]] | None = None, options: AppiumOptions | list[AppiumOptions] | None = None, client_config: AppiumClientConfig | None = None, *, _existing_session: tuple[str, dict[str, Any]] | None = None)#

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

classmethod attach_to(session_id: str, command_executor: str | AppiumConnection = 'http://127.0.0.1:4723', *, capabilities: dict[str, Any] | None = None, client_config: AppiumClientConfig | None = None, extensions: list[type[ExtensionBase]] | None = None) → Self#

Attach to a running session at the given Appium endpoint.

Pass the capabilities returned when the session was created if needed. By default, driver.capabilities is empty. The first command checks whether the session is still active. Calling quit() ends the shared session.

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’

get_status() → dict#

Get the Appium server status

Usage:

driver.get_status()

Returns:

The status information

Return type:

dict

property orientation: str#

Gets the current orientation of the device

Example

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:
  • capabilities – Read appium/appium for more details.

  • browser_profile – Browser profile

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() → Self#

Clears text.

Override for Appium

Returns:

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) → Self#

Simulates typing into the element.

Parameters:

value – A string for typing.

Returns:

appium.webdriver.webelement.WebElement

Module contents#

Appium Python Client: WebDriver module

Remote

alias of WebDriver

class WebElement(parent, id_)

Bases: WebElement

clear() → Self

Clears text.

Override for Appium

Returns:

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) → Self

Simulates typing into the element.

Parameters:

value – A string for typing.

Returns:

appium.webdriver.webelement.WebElement