Appium是跨平台移动端自动化测试框架,支持Android/iOS,原生 / 混合 / Web 应用,使用标准WebDriver协议。
底层驱动:Android用UiAutomator2,iOS用XCUITest。
一、环境搭建Android加Python
1. 安装 Node.js
官网下载 LTS 版本,双击安装。
验证:node -v、npm -v
2. 安装 Java JDK
推荐 JDK 8 或 11,从 Oracle 官网下载。
安装后配置 JAVA_HOME 环境变量,并将 bin 目录加入 Path。
验证:java -version
3. 安装 Android Studio(含 SDK)
下载安装,过程中会自动安装 Android SDK。
配置环境变量:
ANDROID_HOME = SDK 安装目录
Path 中添加 %ANDROID_HOME%\tools 和 %ANDROID_HOME%\platform-tools
验证:adb devices
4. 安装 Appium Server
bash
npm install -g appium
appium -v # 验证
5. 安装驱动
bash
appium driver install uiautomator2
6. (可选)Appium Doctor 检查环境
bash
npm install -g appium-doctor
appium-doctor --android
7. 安装 Python 客户端库
bash
pip install Appium-Python-Client selenium pytest
二、准备测试设备
模拟器:Android Studio 的 AVD Manager 创建。
真机:开启开发者选项和 USB 调试,用 adb devices 确认连接。
三、启动Appium服务
终端执行:
bash
appium
默认地址http://127.0.0.1:4723,保持终端运行。
四、Python测试脚本
python
from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = UiAutomator2Options()
options.platform_name = "Android"
options.device_name = "Android Device"
options.app_package = "com.example.app"
options.app_activity = ".MainActivity"
options.no_reset = True
driver = webdriver.Remote("http://127.0.0.1:4723", options=options)
try:
# 等待并点击登录按钮
login_btn = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((AppiumBy.ID, "com.example.app:id/login_button"))
)
login_btn.click()
# 输入用户名密码
driver.find_element(AppiumBy.ID, "com.example.app:id/username").send_keys("testuser")
driver.find_element(AppiumBy.ID, "com.example.app:id/password").send_keys("testpassword")
driver.find_element(AppiumBy.ID, "com.example.app:id/submit").click()
# 验证登录成功
welcome = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((AppiumBy.ID, "com.example.app:id/welcome_text"))
)
assert "欢迎" in welcome.text
finally:
driver.quit()
五、常用元素定位方式
ID:AppiumBy.ID, "资源id"
Accessibility ID:AppiumBy.ACCESSIBILITY_ID, "content-desc属性值"
Class Name:AppiumBy.CLASS_NAME, "android.widget.EditText"
XPath:AppiumBy.XPATH, "//android.widget.Button[@text='登录']"
Android UIAutomator:AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("登录")'
等待建议:优先使用显式等待(WebDriverWait),避免固定time.sleep()。
六、Appium Inspector定位元素
下载独立版Inspector,连接本地Appium Server(127.0.0.1:4723)。
填入与脚本相同的Capabilities,点击“Start Session”。
点击界面元素即可查看属性,并生成定位表达式。
七、常见问题建议
定位不到元素:检查是否在WebView中(需切换上下文),优先用 ID / Accessibility ID,XPath 尽量简洁。
脚本不稳定:多用显式等待,加入关键断言(如商品名、价格),不要只检查页面跳转。
真机连接失败:确认USB调试授权,重新插拔,adb kill-server再adb devices。
环境问题:运行appium-doctor --android 查看缺失项。