杰瑞科技汇

appium python demo

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

appium python demo-图1
(图片来源网络,侵删)

This guide is designed for beginners and includes:

  1. Prerequisites: What you need to install and set up.
  2. The Demo Script: The complete, runnable Python code.
  3. Code Breakdown: A detailed explanation of each part of the script.
  4. How to Run: Step-by-step instructions to execute the test.
  5. 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 includes adb) 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:

appium python demo-图2
(图片来源网络,侵删)
  1. Open Android Studio.
  2. Go to Tools -> SDK Manager -> SDK Tools.
  3. Check the box for "Android SDK Build-Tools" and "Android SDK Platform-Tools" and click Apply to install them.
  4. Open the AVD Manager (the little phone icon in the toolbar).
  5. Create a new virtual device (e.g., Pixel 4 API 30) and download the system image if prompted.
  6. Once the AVD is created, click on "More Actions" -> "Snapshot" to launch the emulator.
  7. In Android Studio, go to Tools -> Android -> AVD Manager -> Download other system images.
  8. 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.
  9. Launch the emulator with this new image.
  10. 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.apk in 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:

  1. Launch the Appium server.
  2. Connect to the Android emulator.
  3. Open the "ApiDemos" app.
  4. Navigate to "Views" -> "Controls" -> "1. Light Theme".
  5. Find the "Login" button and click it.
  6. Enter a username and password into the provided fields.
  7. Click the "Login" button again.
  8. Verify the login was successful by checking for the success message.
  9. Close the app and quit the session.

Save the following code as appium_demo.py:

appium python demo-图3
(图片来源网络,侵删)
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 running adb devices in your terminal.
    • appPackage: The package name of the app you want to automate. For ApiDemos, it's io.appium.android.apis.
    • appActivity: The main activity of the app to launch. For ApiDemos, it's .ApiDemos.
    • automationName: The automation backend. UiAutomator2 is 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 on localhost:4723 by 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 an AssertionError.
  • try...finally Block:

    • This is a best practice. The code inside the try block contains the main test logic.
    • The code inside the finally block will always run, even if an error occurs in the try block. This is the perfect place to put driver.quit() to ensure your session is closed and resources are freed up.

How to Run

  1. Start the Appium Server:

    • Open the Appium desktop application.
    • Click the "Start Server" button. You should see a message indicating the server is running.
  2. Launch the Emulator:

    Make sure your Android emulator (with the ApiDemos app installed) is running and unlocked.

  3. 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 deviceName in 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.
  • NoSuchElementException:

    • Cause: The script could not find an element with the specified locator.
    • Solution:
      1. Make sure the app is in the correct state (e.g., you've navigated to the right screen).
      2. 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.exe executable is not in your system's PATH environment variable.
    • Solution: Add the path to your Android SDK's platform-tools folder to your system's PATH. For example: C:\Users\<YourUser>\AppData\Local\Android\Sdk\platform-tools.
分享:
扫描分享到社交APP
上一篇
下一篇