簡介
與 Web 元素操作一樣(參考 Selenium Web 元素操作),定位到 APP 控件元素後,可以對控件進行一系列的操作,實現與 APP 交互,比如點擊、文本輸入、元素屬性獲取等。
控件交互常用方法
常見操作
- 點擊方法 element.click()。
- 輸入操作 element.send_keys('appium')。
- 清除操作 element.clear()。
狀態判斷
- 是否可見 element.is_displayed() 返回 True/False。
- 是否可用 element.is_enabled() 返回 True/False。
- 是否被選中 element.is_selected() 返回 True/False。
獲取元素屬性
- 獲取元素屬性:
-
- element.get_attribute()
- resource-id/resourceld 返回 resource-id(API=>18 支持)。
- text 返回 text。
- class 返回 class(API=>18 支持)。
- content-desc/contentDescription 返回 content-desc 屬性。
- checkable,checked,clickable,enabled,focusable,focused 等。
- 獲取元素文本:
-
- 格式:element.text。
- 獲取元素座標:
-
- 格式:element.location。
- 結果:{'y': 19,'x: 498}。
- 獲取元素尺寸(高和寬):
-
- 格式:element.size。
- 結果:{'width':500,'height':22)。
控件操作交互示例
- 打開 ApiDemos.apk。
- 點擊 Animation 進入下個頁面。
- 點擊 Seeking 進入下個頁面。
- 查看【RUN】按鈕是否顯示/是否可點擊。
- 查看【滑動條】是否顯示/是否可點擊。
- 獲取【滑動條】長度。
- 點擊【滑動條】中心位置。
class TestEleOper:
def setup_class(self):
'''
完成 capability 設置
初始化 driver
:return:
'''
# 設置 cpability
caps = {
# 設置 app 安裝的平臺(Android,iOS)
"platformName": "Android",
# 設置 appium 驅動
"appium:automationName": "uiautomator2",
# 設置設備名稱
"appium:deviceName": "emulator-5554",
# 設置被測 app 的包名
"appium:appPackage": "io.appium.android.apis",
# 設置被測 app 啓動頁面的 Activity
"appium:appActivity": ".ApiDemos",
# 不清空緩存信息
"appium:noReset": True,
# 首次啓動的時候,不停止app
"appium:dontStopAppOnReset": True,
# 跳過安裝,權限設置等操作
"appium:skipDeviceInitialization": True
}
# 初始化 driver
self.driver = webdriver.Remote(
"http://127.0.0.1:4723",
options=UiAutomator2Options().load_capabilities(caps)
)
# 添加隱式等待
self.driver.implicitly_wait(10)
def test_ele_oper(self):
'''
點擊滑動條中心位置
:return:
'''
# 點擊 Animation
self.driver.find_element(AppiumBy.ACCESSIBILITY_ID, "Animation").click()
# 點擊 Seeking
self.driver.find_element(AppiumBy.ACCESSIBILITY_ID, "Seeking").click()
# 查看【RUN】按鈕是否顯示/是否可點擊
run_btn_ele = self.driver.find_element(AppiumBy.ID, "io.appium.android.apis:id/startButton")
print(f"RUN按鈕是否顯示 {run_btn_ele.is_displayed()}")
print(f"RUN按鈕是否可點擊 {run_btn_ele.is_enabled()}")
# 查看【滑動條】是否顯示/是否可點擊
seek_bar_ele = self.driver.find_element(AppiumBy.ID, "io.appium.android.apis:id/seekBar")
print(f"滑動條是否顯示 {seek_bar_ele.is_displayed()}")
print(f"滑動條是否可點擊 {seek_bar_ele.is_enabled()}")
# 獲取【滑動條】長度
seek_bar_ele_width = seek_bar_ele.size.get('width')
print(f"滑動條長度爲 {seek_bar_ele_width}")
# 獲取【滑動條】起始位置座標
seek_bar_ele_start = seek_bar_ele.location
print(f"滑動條起始位置座標爲 {seek_bar_ele_start}")
# 獲取【滑動條】中間位置座標
seek_bar_center_x = seek_bar_ele_start.get("x") + seek_bar_ele_width/2
seek_bar_center_y = seek_bar_ele_start.get("y")
seek_bar_center = (seek_bar_center_x, seek_bar_center_y)
print(f"滑動條中間位置座標爲 {seek_bar_center}")
# 點擊【滑動條】中間位置
self.driver.tap([seek_bar_center], 1000)
總結
常見控件的基本交互方式,可以模擬用戶與應用程序的交互。在編寫測試腳本時,通常需要結合元素的定位方式(如 ID、XPath 等)來找到相應的控件元素。確保測試腳本中的等待和定位策略,以及對元素狀態的驗證,可以提高測試的穩定性和可靠性。