Of course! Here is a comprehensive and well-commented Appium Python demo that automates a simple login flow on a sample Android application.

This guide is designed for beginners and includes:
- Prerequisites: What you need to install and set up.
- The Demo Script: The complete, runnable Python code.
- Code Breakdown: A detailed explanation of each part of the script.
- How to Run: Step-by-step instructions to execute the test.
- Troubleshooting: Common issues and their solutions.
Prerequisites
Before running the code, you need to have the following set up:
A. Software:
- Python 3: Make sure you have Python 3.6 or newer installed.
- Appium Server: Download and install Appium from the official website.
- Android Studio: To manage the Android SDK, create virtual devices (AVDs), and get the sample app.
- Java Development Kit (JDK): Appium requires Java. Install JDK 8 or 11.
- Android SDK: Comes bundled with Android Studio. Make sure the
platform-tools(which includesadb) are installed.
B. The Sample App: We will use the "ApiDemos" app, which is a standard Android app for testing. The easiest way to get it is:

- Open Android Studio.
- Go to Tools -> SDK Manager -> SDK Tools.
- Check the box for "Android SDK Build-Tools" and "Android SDK Platform-Tools" and click Apply to install them.
- Open the AVD Manager (the little phone icon in the toolbar).
- Create a new virtual device (e.g., Pixel 4 API 30) and download the system image if prompted.
- Once the AVD is created, click on "More Actions" -> "Snapshot" to launch the emulator.
- In Android Studio, go to Tools -> Android -> AVD Manager -> Download other system images.
- Select an API level (e.g., API 30), an ABI (e.g., x86_64), and download the system image for the Google Play Intel x86 Atom_64 system.
- Launch the emulator with this new image.
- In a terminal, run the following command to install the ApiDemos app:
adb install path/to/your/sdk/samples/android-30/ApiDemos-debug.apk
You can usually find the
ApiDemos-debug.apkin your Android SDK directory, e.g.,C:\Users\<YourUser>\AppData\Local\Android\Sdk\samples\android-30\ApiDemos-debug.apk.
C. Python Libraries:
You need to install the Appium-Python-Client library. Open your terminal or command prompt and run:
pip install Appium-Python-Client
The Demo Script
This script will:
- Launch the Appium server.
- Connect to the Android emulator.
- Open the "ApiDemos" app.
- Navigate to "Views" -> "Controls" -> "1. Light Theme".
- Find the "Login" button and click it.
- Enter a username and password into the provided fields.
- Click the "Login" button again.
- Verify the login was successful by checking for the success message.
- Close the app and quit the session.
Save the following code as appium_demo.py:

import time
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
# --- 1. Define Desired Capabilities ---
# These are the configuration settings for Appium to know how to connect to your device/app.
caps = {
"platformName": "Android",
"deviceName": "Pixel_4_API_30", # You can find this name in AVD Manager
"appPackage": "io.appium.android.apis",
"appActivity": ".ApiDemos",
"automationName": "UiAutomator2" # Modern and recommended for Android
}
# --- 2. Initialize the WebDriver ---
# This connects your script to the Appium server and starts the session.
print("Initializing Appium driver...")
driver = webdriver.Remote('http://localhost:4723/wd/hub', caps)
# Add an implicit wait to wait for elements to appear before throwing an exception
driver.implicitly_wait(10)
try:
# --- 3. Test Steps ---
# Step 1: Navigate to the login screen
print("Navigating to the login screen...")
# Find the 'Views' element and click it
views_element = driver.find_element(AppiumBy.ID, "android:id/text1")
views_element.click()
# Find the 'Controls' element and click it
controls_element = driver.find_element(AppiumBy.ID, "android:id/text1")
controls_element.click()
# Find the '1. Light Theme' element and click it
# We use XPath here to be more specific, as 'text1' ID is reused.
light_theme_element = driver.find_element(AppiumBy.XPATH, "//android.widget.TextView[@text='1. Light Theme']")
light_theme_element.click()
# Step 2: Enter username and password
print("Entering credentials...")
# Find the username field and enter text
username_field = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_username")
username_field.send_keys("testuser")
# Find the password field and enter text
password_field = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_password")
password_field.send_keys("password123")
# Step 3: Click the Login button
print("Clicking the Login button...")
login_button = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_button")
login_button.click()
# Step 4: Verify the login was successful
print("Verifying login...")
# After login, a success message appears. We wait for it and check its text.
success_message = driver.find_element(AppiumBy.ID, "io.appium.android.apis:id/login_response")
assert "success" in success_message.text.lower()
print("Login successful! Message found:", success_message.text)
# Pause to see the result on the screen
time.sleep(3)
finally:
# --- 4. Quit the Driver ---
# This is crucial to end the session and close the app.
print("Quting the driver session.")
driver.quit()
print("Test finished successfully.")
Code Breakdown
-
Import Libraries:
time: Used for adding a pause (time.sleep()) to visually inspect the screen.webdriver: The main class from the Appium-Python-Client that controls the device.AppiumBy: A class that provides locators (like ID, XPath, Accessibility ID) to find elements.
-
Desired Capabilities (
caps):- This dictionary is the most important part. It tells Appium everything it needs to know.
platformName: "Android".deviceName: The name of your emulator or device. You can find this in the AVD Manager or by runningadb devicesin your terminal.appPackage: The package name of the app you want to automate. For ApiDemos, it'sio.appium.android.apis.appActivity: The main activity of the app to launch. For ApiDemos, it's.ApiDemos.automationName: The automation backend.UiAutomator2is the modern, default, and recommended choice for Android.
-
Initialize the WebDriver:
webdriver.Remote('http://localhost:4723/wd/hub', caps): This line connects to the Appium server (which runs onlocalhost:4723by default) and starts a new session using the capabilities you defined.driver.implicitly_wait(10): This tells the driver to wait up to 10 seconds for an element to appear if it's not immediately available. This makes your script more robust.
-
Test Steps:
driver.find_element(): This is the core command to find a single UI element. It takes two arguments: the locator strategy (AppiumBy.ID,AppiumBy.XPATH, etc.) and the locator value.element.click(): Simulates a tap on the found element.element.send_keys("text"): Simulates typing text into a text field.assert "success" in success_message.text.lower(): This is a simple verification. It checks if the word "success" is present in the text of the success message. If not, the script will stop with anAssertionError.
-
try...finallyBlock:- This is a best practice. The code inside the
tryblock contains the main test logic. - The code inside the
finallyblock will always run, even if an error occurs in thetryblock. This is the perfect place to putdriver.quit()to ensure your session is closed and resources are freed up.
- This is a best practice. The code inside the
How to Run
-
Start the Appium Server:
- Open the Appium desktop application.
- Click the "Start Server" button. You should see a message indicating the server is running.
-
Launch the Emulator:
Make sure your Android emulator (with the ApiDemos app installed) is running and unlocked.
-
Run the Python Script:
- Open a terminal or command prompt.
- Navigate to the directory where you saved
appium_demo.py. - Run the script with the command:
python appium_demo.py
You should see the Appium logs in the Appium Desktop window and your emulator will perform the automated steps. The Python terminal will print the status messages from the script.
Troubleshooting
-
Unable to connect to http://localhost:4723/wd/hub:- Cause: The Appium server is not running.
- Solution: Click "Start Server" in the Appium Desktop application.
-
An unknown server-side error occurred while processing the command:- Cause: The
deviceNamein your capabilities does not match the name of your running emulator. Or the emulator is not unlocked. - Solution: Double-check the device name in the AVD Manager. Make sure the emulator is on its home screen and unlocked.
- Cause: The
-
NoSuchElementException:- Cause: The script could not find an element with the specified locator.
- Solution:
- Make sure the app is in the correct state (e.g., you've navigated to the right screen).
- Inspect the Element: The best way to fix this is to use the Appium Desktop Inspector.
- In Appium Desktop, click the "Start Inspector Session" button.
- Enter your desired capabilities and click "Start Session".
- This will open a window showing the current screen of your app. You can click on elements to see their exact locators (ID, XPath, etc.). Use these updated locators in your script.
-
ADB is not recognized as an internal or external command...:- Cause: The
adb.exeexecutable is not in your system's PATH environment variable. - Solution: Add the path to your Android SDK's
platform-toolsfolder to your system's PATH. For example:C:\Users\<YourUser>\AppData\Local\Android\Sdk\platform-tools.
- Cause: The
