uiautomator2 for Android UI Automation

3.5.0 · active · verified Thu Apr 16

uiautomator2 is a Python wrapper for Google's UiAutomator test framework, enabling robust UI automation for Android devices. It simplifies interacting with Android applications, performing actions like clicking, typing, scrolling, and getting device information. The current stable version is 3.5.0, with frequent patch releases addressing bug fixes and minor enhancements. It requires Python 3.8 to 3.11.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an Android device using `uiautomator2`, retrieve device information, take a screenshot, press the home button, and dump the UI hierarchy. Remember to run `u2 init` on your device first to set up the necessary server applications.

import uiautomator2 as u2
import os

# Connect to a device. You can specify a serial (e.g., 'emulator-5554')
# or an IP address (e.g., '192.168.1.100'). If no argument is given,
# it tries to connect to the first available device via ADB.
# Ensure 'adb devices' shows your device and 'u2 init' has been run on the device.

# Example for connecting to a specific IP, fallback to default
DEVICE_ADDRESS = os.environ.get('U2_DEVICE_ADDRESS', None)

try:
    if DEVICE_ADDRESS:
        d = u2.connect(DEVICE_ADDRESS)
    else:
        d = u2.connect() # Connects to the default/first available device
    
    print(f"Successfully connected to device: {d.info.get('serial', 'N/A')}")

    # Print basic device information
    print("Device Info:", d.info)

    # Get the current package and activity
    current_app = d.app_current()
    print(f"Current app: {current_app['package']} / {current_app['activity']}")

    # Take a screenshot and save it
    screenshot_path = "uiautomator2_quickstart_screenshot.png"
    d.screenshot(screenshot_path)
    print(f"Screenshot saved to {screenshot_path}")

    # Interact with the UI (example: press the Home button)
    d.press("home")
    print("Pressed Home button.")

    # Dump the current UI hierarchy (useful for inspecting elements)
    xml_dump = d.dump_hierarchy()
    print("UI Hierarchy (first 200 characters):", xml_dump[:200])

except Exception as e:
    print(f"An error occurred: {e}")
    print("\nTroubleshooting steps:")
    print("1. Ensure your Android device is connected via USB/WiFi and ADB debugging is enabled.")
    print("2. Run 'adb devices' in your terminal to confirm ADB detects your device.")
    print("3. Run 'python -m uiautomator2 init' (or 'u2 init') to install the uiautomator2 server on the device.")
    print("4. If connecting via IP, ensure the device is on the same network and you're using the correct IP.")

view raw JSON →