Python+Appium自动化测试(11)-location与size获取元素坐标

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),然后点击删除。

# @author: 给你一页白纸

# 第一个聊天框元素
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()
posted @ 2020-09-17 18:35  给你一页白纸  阅读(1655)  评论(0编辑  收藏  举报