Appium實戰-元素定位
元素定位有時候很簡單,有時候也很頭疼,對于原生的定位方式很簡單,對于混合編程和跨平臺來說,定位方式就復雜了。有時候使用工具進行定位之后,代碼運行起來卻定位不到。
因為我們的app是跨平臺應用uni-app,所以下面的講述就以uni-app定位方式,也會將各種場景中的問題一一展示。
工具
自動化框架:Appium2
定位工具:Appium Inspector(網頁版)。定位工具的選擇一般選擇對應的自動化框架,否則有可能會出現問題。
怎么安裝和使用這里不做講解,百度都能搜索
Capability配置如下:
{
"platformName": "Android",
"appium:automationName": "uiautomator2",
"appium:deviceName": "3e4f046e",
"appium:appPackage": "io.dcloud.UNI0F29818.dis",
"appium:appActivity": "io.dcloud.PandoraEntry",
"appium:platformVersion": "15",
"appium:ignoreHiddenApiPolicyError": true,
"appium:disableWindowAnimation": true,
"appium:enforceAppInstall": true
}
定位方式
1.常規定位方式。如圖,可以使用id, -android uiautomator, xpath等,根據右側能直接定位的方式,選擇簡單的,直接照抄就行
driver.find_element(AppiumBy.XPATH, "//*[@class='android.widget.Toast']") driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("設備")') driver.find_element(AppiumBy.ACCESSIBILITY_ID, '異常')

常見問題
1.定位不到,uni-app頁面跳轉或者彈窗有時會定位不到,使用Appium Inspector檢測仍然顯示上一個頁面元素
解決方案:使用坐標定位 driver.tap([(222, 2224)], 100)
2.列表或者頁面比較長,手機屏幕顯示不全,需要進行滑動
方法一:滑動定位,滑動直到找到元素。(有限制,只會滑動幾次,不能一直滑動)
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().text("保存").instance(0))').click()
方法二:滑動。滑動到元素位置之后,使用上述常規方法進行定位,如果定位不到元素,使用坐標定位
# 上滑 def swipe_up(self, driver, duration=200): size = driver.get_window_size() start_x = size['width'] // 2 start_y = size['height'] * 0.8 # 起始點 Y 坐標為屏幕高度 80% end_y = size['height'] * 0.2 # 終點 Y 坐標為屏幕高度 20% driver.swipe(start_x, start_y, start_x, end_y, duration) # 下滑 def swipe_down(self, driver, duration=200): size = driver.get_window_size() start_x = size['width'] // 2 start_y = size['height'] * 0.2 # 起始點 Y 坐標為屏幕高度 80% end_y = size['height'] * 0.8 # 終點 Y 坐標為屏幕高度 20% driver.swipe(start_x, start_y, start_x, end_y, duration)
3.Android13以上輸入框無法輸入,無法使用send_keys()方法進行輸入
解決方法:使用物理鍵進行輸入。實際輸入跟物理鍵不同,需要進行映射,下面是一個完整的封裝。
class KeyCodeActions: def __init__(self, driver): self.driver = driver # 定義常見按鍵的 keycode 映射 self.keycodes = { # 常用硬件鍵 "home": 3, "back": 4, "volume_up": 24, "volume_down": 25, "enter": 66, "menu": 82, "search": 84, "camera": 27, "power": 26, # 數字鍵 0-9 "0": 7, "1": 8, "2": 9, "3": 10, "4": 11, "5": 12, "6": 13, "7": 14, "8": 15, "9": 16, # 字母鍵 A-Z "a": 29, "b": 30, "c": 31, "d": 32, "e": 33, "f": 34, "g": 35, "h": 36, "i": 37, "j": 38, "k": 39, "l": 40, "m": 41, "n": 42, "o": 43, "p": 44, "q": 45, "r": 46, "s": 47, "t": 48, "u": 49, "v": 50, "w": 51, "x": 52, "y": 53, "z": 54, } def press_key(self, key_name): """根據按鍵名稱按下對應的鍵""" if key_name in self.keycodes: self.driver.press_keycode(self.keycodes[key_name]) else: print(f"按鍵 '{key_name}' 不存在!") if __name__ == '__main__': number = "18288889999" for i in number: KeyCodeActions.press_key(i)

浙公網安備 33010602011771號