在做自動化的過程中都會遇到一些無法定位到的地方,或者通過元素怎么都定位不成功的地方,這個時候我們可以使用必殺技,通過坐標定位。具體的怎么操作呢?
swipe點擊事件
前面安靜寫過一篇關於swipe的滑動app頁面的,其實swipe也可以模擬點擊事件,只要我們把后面的響應時間變小,然后坐標變成同一個坐標。詳情swipe的用法可以參考appium---App頁面滑動
通過工具查看到這個登錄/注冊按鈕坐標為[390,831][522,873],算得出來大概坐標為[470,850]
話不多說直接上代碼,通過swipe進行模擬點擊(注冊/登錄)按鈕
# coding:utf-8 from appium import webdriver import time desired_caps = { 'platformName': 'Android', # 測試版本 'deviceName': 'emulator-5554', # 設備名 'platformVersion': '5.1.1', # 系統版本 "appPackage": "com.taobao.taobao", # app包名 "appActivity": "com.taobao.tao.welcome.Welcome", # 啟動launch Activity "noReset": True, # 不清空數據 } driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) # 淘寶加載慢,加個延遲。 time.sleep(16) x1 = int(470) y1 = int(850) driver.swipe(x1,y1,x1,y1,500)
一個方法可以多種用法,但是python怎么會這樣對待我們呢?當然有比這更好的方法
tap
tap方法表示點擊事件,通過坐標的方式進行點擊,一般用於元素難於定位的時候
源碼
def tap(self, positions, duration=None): """Taps on an particular place with up to five fingers, holding for a certain time # 用五指輕敲一個特定的地方,保持一定的時間 :Args: - positions - an array of tuples representing the x/y coordinates of # 表示x/y坐標的元組數組 the fingers to tap. Length can be up to five. - duration - (optional) length of time to tap, in ms # 持續時間單位毫秒 :Usage: driver.tap([(100, 20), (100, 60), (100, 100)], 500) """
這里我們可以直接通過右側bonds屬性上坐標直接定位,不用我們在一個個計算
# coding:utf-8 from appium import webdriver import time desired_caps = { 'platformName': 'Android', # 測試版本 'deviceName': 'emulator-5554', # 設備名 'platformVersion': '5.1.1', # 系統版本 "appPackage": "com.taobao.taobao", # app包名 "appActivity": "com.taobao.tao.welcome.Welcome", # 啟動launch Activity "noReset": True, # 不清空數據 } driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) time.sleep(16) # 通過tap模擬點擊 driver.tap([(390,831),(522,873)],500)
注意:更換手機跑腳本的時候,我們一定要更換坐標,每個手機的坐標可能都不同。
其實方法還有很多種,這里就先不一個個介紹了,持續更新中~~~