uiautomator2+python封装简单的上下或左右查找元素的方法
使用d.dump_hierarchy() 截取当前页面所有元素,假如滑动到底部,那么页面元素不会变更,所以可以判断滑动到底部或者顶部。
但是使用d.dump_hierarchy()会页面截取所有信息,其中包括时间和实时流量,这些每秒钟都会变更的,所有为了屏蔽部分信息,我从页面信息的百分之50开始获取,不同手机可能不一样,这些代码在小米k20Pro上可以正常运行,各位大佬要是有更好的方法可在下方评论交流交流。
class BaseAction():
def __init__(self,driver=None):
self.d=u2.connect_usb(driver)
def get_parameter(self,parameter,x=0.5, ys=0.8, ye=0.3):
"""
从坐标xx,ys滑动到xx,ye,假如没有找到元素则从xx,ye滑动到xx,ys查找元素,默认上下滑动查找元素
"""
while True:
try:
set_parameter = self.d.xpath(parameter).get(timeout=1)
# 找到元素则返回找到的元素
return set_parameter
# 没找到元素则进行下滑
except Exception:
page_source = self.d.dump_hierarchy()[int(len(self.d.dump_hierarchy())*0.5):]
self.d.swipe(x, ys, x, ye)
# 截取当前页面所有元素,页面元素没有变化时跳出循环
time.sleep(1)
#从百分之50的部分开始截取并对比
if self.d.dump_hierarchy()[int(len(self.d.dump_hierarchy())*0.5):] == page_source:
break
while True:
try:
set_parameter = self.d.xpath(parameter).get(timeout=1)
# 找到元素则返回找到的元素
return set_parameter
# 没找到元素则进行下滑
except Exception:
page_source = self.d.dump_hierarchy()[int(len(self.d.dump_hierarchy())*0.5):]
self.d.swipe(x, ye, x, ys)
# 截取当前页面所有元素,页面元素没有变化时跳出循环
time.sleep(1)
# 从百分之50的部分开始截取并对比
if self.d.dump_hierarchy()[int(len(self.d.dump_hierarchy())*0.5):] == page_source:
break