文章轉自:https://www.cnblogs.com/lfr0123/p/13686769.html
appium做app自動化測試過程中,有時需要獲取控件元素的坐標進行滑動操作。appium中提供了location方法獲取控件元素左上角的坐標,再通過size方法獲取控件元素的寬高,就可以得到控件元素更多的坐標。
一,獲取元素坐標的方法
1,size獲取元素的寬、高
ele_size = driver.find_element_by_xx('xx').size # 元素的寬 width = ele_size['width'] # 元素的高 height = ele_size['height']
2,location獲取元素左上角坐標
ele_coordinate = driver.find_element_by_xx('xx').location # 元素左上角橫坐標 x = ele_coordinate['x'] # 元素左上角縱坐標 y = ele_coordinate['y']
3,由此可以計算出元素其他的坐標
(x+width, y) # 右上角坐標 (x+width, y+height) # 右下角坐標 (x, y+height) # 左下角坐標 (x+width/2, y+height/2) # 元素中心點坐標
二,使用場景
需要對元素進行滑動時,我們可以考慮先獲取元素的坐標,再通過坐標來滑動元素。
如:QQ聊天界面刪除某個聊天。從元素的右上角 (x+width, y) 向左滑動至上邊中心點(x+width/2, y),然后點擊刪除。
# 第一個聊天框元素 ele = driver.find_element_by_xpath('//android.widget.AbsListView/android.widget.LinearLayout[@index=1]') # 聊天元素的寬 width = ele.size['width'] # 左上角坐標 x = ele.location['x'] y = ele.location['y'] # 滑動起始坐標 start_x = x + width start_y = y # 滑動結束坐標 end_x = x + width/2 end_y = y # 滑動並刪除 action = TouchAction(driver) action.press(start_x, start_y).move_to(end_x, end_y).release().perform() driver.find_element_by_xpath('//*[@content-desc="刪除"]').click()