杰瑞科技汇

如何用Python操作Selendroid?

Of course! Here is a comprehensive guide on using Selendroid with Python.

如何用Python操作Selendroid?-图1
(图片来源网络,侵删)

What is Selendroid?

First, a quick definition. Selendroid is a test automation framework for Android. It's a "drop-in" replacement for the popular Appium server. While Appium can automate iOS, Android, and more, Selendroid is specialized only for Android.

Its key features are:

  • No Jailbreak/Root Required: It works on real devices and emulators without special permissions.
  • Based on Selenium WebDriver: If you know Selenium, the concepts are very similar.
  • Automates Native, Hybrid, and Web Apps: It can interact with any Android app.
  • Standalone Server: You run a Java server that your Python scripts will connect to.

How Selendroid Differs from Appium

Feature Selendroid Appium
Primary Focus Android only Cross-platform (iOS, Android, Web)
Architecture Standalone Java server Node.js server with plugins
Setup Simpler, fewer dependencies More complex, requires Node.js, Appium server
Stability Very mature and stable Very active development, can be less stable
Community Smaller, more niche Very large and active

When to choose Selendroid: If your project is 100% Android, you want a simple, stable setup, and you don't need iOS automation.


Prerequisites

Before you start, you need to have the following installed:

如何用Python操作Selendroid?-图2
(图片来源网络,侵删)
  1. Java Development Kit (JDK): Selendroid is a Java application. You need JDK 8 or later.
    • Verify with: java -version
  2. Android SDK: You need the Android SDK to manage emulators and get tools like adb.
  3. Android Emulator: A running Android emulator (e.g., via Android Studio) or a physical Android device connected via USB with "USB Debugging" enabled.
  4. Python and Pip: Make sure you have Python 3 and pip installed.
    • Verify with: python --version and pip --version
  5. Selendroid Server JAR: The core of the framework. You'll download this file.

Step-by-Step Guide to Setup and Run a Test

Step 1: Download the Selendroid Server

  1. Go to the official Selendroid releases page: https://github.com/selendroid/selendroid/releases
  2. Download the latest selendroid-standalone-<version>.jar file.
  3. Place the JAR file in a convenient location, for example, C:\selendroid on Windows or ~/selendroid on macOS/Linux.

Step 2: Start the Selendroid Server

You need to tell Selendroid which Android device/emulator to connect to. You can get the device ID using adb devices.

  1. Open a terminal/command prompt.
  2. Run adb devices. You should see your emulator listed, e.g., emulator-5554.
  3. Navigate to the directory where you saved the JAR file and start the server, pointing it to your device.
# The -port flag is optional, default is 4444
java -jar selendroid-standalone-<version>.jar -port 4444 -verbose

Example:

cd ~/selendroid
java -jar selendroid-standalone-0.17.0.jar -port 4444 -verbose

You should see output indicating the server is running and waiting for connections.

Step 3: Install Your Test App (APK)

Selendroid needs the APK (Android Package) of the app you want to test.

如何用Python操作Selendroid?-图3
(图片来源网络,侵删)
  1. Place your app's APK file in a known location.
  2. Use the selendroid command-line tool (included in the release zip) to install it on the device and prepare it for automation.
# Syntax: java -jar selendroid-standalone.jar -app <path_to_apk>
java -jar selendroid-standalone-0.17.0.jar -app /path/to/your/app.apk

This will install the app and generate a selendroid-test-app-<version>.apk on your device, which is the instrumented version used for testing.

Step 4: Write the Python Test Script

Now for the fun part! We'll use the standard selenium Python library. It's the same library you'd use for web automation.

First, install the Selenium library if you haven't already:

pip install selenium

Here is a complete Python script to launch the app, perform a simple action, and quit.

test_selendroid.py

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
# --- Configuration ---
# The URL to connect to the Selendroid server
# We specify the APK we installed in the previous step
DESIRED_CAPS = {
    'platformName': 'Android',
    'deviceName': 'emulator-5554',  # Use the device ID from 'adb devices'
    'app': 'path/to/your/app.apk',  # The path to the original APK on your computer
    'appPackage': 'com.example.myapp', # The package name of your app
    'appActivity': '.MainActivity',   # The main activity to start
    'automationName': 'Selendroid'    # Explicitly tell Selenium to use Selendroid
}
# --- Test Execution ---
try:
    # 1. Initialize the WebDriver
    # The URL points to the Selendroid server we started
    driver = webdriver.Remote('http://localhost:4444/wd/hub', DESIRED_CAPS)
    # 2. Perform some actions
    # Selendroid gives elements special IDs. You can find them using tools like uiautomator2.
    # Let's assume we have a button with ID "my_button_id"
    print("Looking for button...")
    button = driver.find_element(By.ID, 'my_button_id')
    button.click()
    print("Button clicked!")
    # Let's assume a text view with ID "result_text" appears
    print("Looking for result text...")
    result_text = driver.find_element(By.ID, 'result_text')
    print(f"Result text is: {result_text.text}")
    # 3. Wait for a few seconds to see the result (optional)
    time.sleep(3)
    # 4. Quit the driver
    driver.quit()
    print("Test completed successfully!")
except NoSuchElementException as e:
    print(f"Element not found: {e}")
    driver.quit()
except Exception as e:
    print(f"An error occurred: {e}")
    driver.quit()

Step 5: Run the Test

  1. Make sure your Selendroid server is running.
  2. Make sure your Android emulator/device is connected.
  3. Run the Python script from your terminal:
python test_selendroid.py

If everything is set up correctly, you will see the emulator screen, the app will launch, the button will be clicked, and the script will print the result from the text view.


How to Find Element Locators (The Hard Part)

This is the most challenging aspect of mobile automation. Here are the common strategies for finding element IDs in Selendroid:

  1. Android UI Automator (Recommended):

    • This is the most powerful method. It uses a small library that runs on the device to query the UI.

    • Syntax: new UiSelector().<property>()

    • Example in Python:

      # Find a button by its text content
      button = driver.find_element(By.ID, 'new UiSelector().text("Click Me")')
      # Find an element by its resource ID (the best way if possible)
      # The format is: 'package_name:id/resource_name'
      element = driver.find_element(By.ID, 'com.example.myapp:id/my_text_view')
  2. Accessibility IDs:

    • If developers set contentDescription in the XML layout, you can use that as a locator. Selendroid often exposes this.
    • Syntax: driver.find_element(By.ACCESSIBILITY_ID, 'content_description_value')
  3. XPath:

    • Can be slow and brittle on mobile, but works. Be as specific as possible.
    • Example: driver.find_element(By.XPATH, '//android.widget.TextView[@text="Welcome"]')
  4. Class Name:

    • Less specific, but useful for lists.
    • Example: driver.find_elements(By.CLASS_NAME, 'android.widget.ListView')

Modern Alternative: Appium with Python

While Selendroid is a great tool, Appium is now the de-facto standard for mobile automation. It has a much larger community, better support for newer Android versions, and a more active development lifecycle.

The good news is that the Python code for Appium is almost identical to Selendroid! You only need to change the capabilities.

Here is how you would write the same test using Appium:

test_appium.py

import time
from appium import webdriver # Use the 'appium' library instead of 'selenium'
# --- Configuration ---
DESIRED_CAPS = {
    'platformName': 'Android',
    'deviceName': 'emulator-5554',
    'app': 'path/to/your/app.apk',
    'appPackage': 'com.example.myapp',
    'appActivity': '.MainActivity',
    # The only change is 'automationName' and using 'appium' driver
    'automationName': 'UiAutomator2' # The modern Appium automation engine
}
# --- Test Execution ---
try:
    # The URL is the same
    driver = webdriver.Remote('http://localhost:4723/wd/hub', DESIRED_CAPS) # Appium default port is 4723
    # The rest of the code is identical!
    button = driver.find_element(By.ID, 'com.example.myapp:id/my_button_id')
    button.click()
    print("Button clicked!")
    result_text = driver.find_element(By.ID, 'com.example.myapp:id/result_text')
    print(f"Result text is: {result_text.text}")
    time.sleep(3)
    driver.quit()
    print("Appium test completed successfully!")
except Exception as e:
    print(f"An error occurred: {e}")
    driver.quit()

Conclusion

Selendroid Appium
Pros Simple setup, stable, Android-specific Huge community, cross-platform, active development, better for modern Android
Cons Smaller community, not actively developed for new features Can be complex to set up, steeper learning curve
Python Code Uses selenium library Uses appium library (very similar syntax)

For any new project, Appium is generally the recommended choice due to its future-proof nature and extensive support. However, if you have an existing Selendroid test suite or a simple, Android-only project, Selendroid remains a perfectly valid and effective tool. The transition between the two in Python is very smooth.

分享:
扫描分享到社交APP
上一篇
下一篇