1. Nguyên lý hoạt động của Appium trên nền tảng Android
Bootstrap.jar là gì?
Bootstrap.jar là thành phần cốt lõi của Appium được triển khai dưới dạng ứng dụng UiAutomator trên thiết bị Android. Thành phần này khởi tạo một máy chủ socket nhận lệnh từ Appium Server và chuyển tiếp cho hệ thống UiAutomator để thực thi.
2. Cài đặt và cấu hình môi trường
- Cài đặt Python 3.x trở lên
- Cài JDK 8 hoặc phiên bản mới hơn
- Thiết lập Appium Desktop qua giao diện đồ họa
- Thực hiện lệnh
pip install Appium-Python-Clientđể cài gói điều khiển - Cài Android Studio để có công cụ uiautomatorviewer tại
C:\Users\xxx\AppData\Local\Android\Sdk\tools\bin - Nên sử dụng Windows 10 để tránh lỗi khi xác định thành phần giao diện
3. Khởi động ứng dụng qua script
from appium import webdriver
config = {
'platformName': 'Android',
'platformVersion': '7.1',
'deviceName': 'Nexus 5X',
'appPackage': 'com.miui.calculator',
'appActivity': '.cal.CalculatorActivity',
'noReset': True,
'unicodeKeyboard': True,
'settings[waitForIdleTimeout]': 100
}
session = webdriver.Remote('http://localhost:4723/wd/hub', config)
Các tham số trong cấu hình phải đầy đủ. Có thể xác định appPackage và appActivity bằng:
adb logcat | grep Displayeddumpsys activity | grep mFocusedActivityadb shell dumpsys window | grep mCurrentFocus
4. Phương pháp truy xuất thành phần giao diện
Sử dụng uiautomatorviewer hoặc Appium Desktop để phân tích giao diện:
- Xpath:
- Định vị tuyệt đối:
/hierarchy/android.widget.FrameLayout[1]/... - Định vị tương đối:
//android.widget.TextView[@text='Tính năng'] - Ví dụ:
session.find_element_by_xpath("//*[@resource-id='btn_1']")
- Định vị tuyệt đối:
- ID:
session.find_element_by_id("com.miui.calculator:id/btn_1_s") - Content Description:
session.find_element_by_accessibility_id("Mô tả") - Định vị qua mối quan hệ:
session.find_element_by_xpath( "//*[contains(@text, 'RE')]/following-sibling::android.widget.TextView" )
5. Các thao tác điều khiển thành phần
- Click:
element.click() - Lấy nội dung:
element.text - Nhập liệu:
session.find_element_by_id("editor").send_keys("Chào mừng") - Xóa dữ liệu:
element.clear() - Di chuyển màn hình:
size = session.get_window_size() session.swipe(size['width']/2, size['height']*3/4, size['width']/2, size['height']/4) - Phím tắt:
session.press_keycode(4)
6. Lệnh ADB thông dụng
- Xóa cache ứng dụng:
adb shell pm clear com.xiaomi.router - Kết thúc và khởi động lại:
adb shell am start -n com.xiaomi.router/.main.MainActivity -S - Trích xuất giao diện:
adb shell uiautomator dump - Xem phiên bản:
adb shell dumpsys package com.huawei.genexcloud.speedtest | grep -i versionname
7. Cơ chế chờ trong Appium
- Chờ ngầm định:
session.implicitly_wait(10) - Chờ điều kiện:
from selenium.webdriver.support.ui import WebDriverWait def check_popup(driver): try: driver.find_element_by_id("btn_cancel").click() return True except: return False WebDriverWait(session, 20).until(check_popup)