最近在用appium做自動化時發現,有一些元素無法通過uiautomatorviewer進行定位,這樣就只能通過相對坐標來進行定位了。但是,問題又來了:如何獲取元素的坐標呢?
在網上找了半天也沒找到相應的解決方法,后來在testerhome一篇文章中看到打開手機指針位置來確定元素所在坐標。具體方法:設置--開發者選項--指針位置
開啟指針位置之后,點擊手機屏幕就會顯示該位置的具體坐標,這樣就獲取到了元素的絕對坐標 然后通過webdriver的tap()函數點擊該坐標就可以了。
我們獲取到的是絕對坐標,如果換一個屏幕分辨率不同的手機那這個坐標自然會發生變化,要實現不同手機均能實現點擊同一控件自然要用到相對坐標了,具體方法如下:
1.獲取當前空間的絕對坐標(x1,y1),開啟指針位置后,通過點擊控件位置獲取坐標;
2.獲取當前手機的屏幕大小(x2,y2),通過driver.get_window_size()['width'],dirver.get_window_size()['height']分辨獲取當前手機的x、y坐標;
3.獲取測試手機的屏幕大小(x3,y3),獲取方式同上一步;
4.獲取指定控件在測試手機中的坐標:((x1/x2)*x3,(y1/y2)*y3)
5.獲取到坐標之后同樣使用tap()函數點擊該控件。
具體代碼如下:
# -*-encoding:utf-8 -*- import os import unittest import HTMLTestRunner from test_platform import URL from test_platform import platform from appium import webdriver from time import sleep # 設定系數 a = 554.0/1080 b = 1625.0/1794 class Login(unittest.TestCase): def setUp(self): platform['appPackage'] = 'com.xxxxxxxxx' platform['appActivity'] = '.ui.activity.LoginActivity' #platform['appWaitActivity'] = '.MainActivity_' desired_caps = platform self.driver = webdriver.Remote(URL,desired_caps) self.driver.implicitly_wait(30) def tearDown(self): self.driver.quit() def test_login(self): el = self.driver.find_element_by_xpath("\ //android.widget.TextView[contains(@resource-id,'com.xxxxx/etRole')]") if el: el.click() # 以xml格式打印當前頁面內容 # print self.driver.page_source.encode("utf-8") # self.driver.find_element_by_name("家長").click() # 獲取當前手機屏幕大小X,Y X = self.driver.get_window_size()['width'] Y = self.driver.get_window_size()['height'] # 屏幕坐標乘以系數即為用戶要點擊位置的具體坐標,當前app內為選擇用戶角色為“家長” self.driver.tap([(a*X, b*Y)],) # 輸入手機號碼 self.driver.find_element_by_xpath("\ //android.widget.EditText[contains(@resource-id,'com.xxxxx:id/etAccount')]")\ .send_keys("***********") # 輸入密碼 self.driver.find_element_by_xpath("\ //android.widget.EditText[contains(@resource-id,'com.xxxxxx.qh:id/etPasswd')]") \ .send_keys("123456") # 點擊登錄按鈕 self.driver.find_element_by_xpath("\ //android.widget.Button[contains(@resource-id,'com.xxxxxx:id/btnLogin')]").click() sleep(5) # 當前賬號存在多個孩子,選擇孩子后登錄app self.driver.find_element_by_xpath("\ //android.widget.TextView[contains(@text,'徐熙媛')]").click() if __name__ == '__main__': unittest.main()
參考:https://testerhome.com/topics/1559
