toast是android中用来显示信息的一种机制,和dialog对话框不一样的是toast是没有焦点的,而且toast显示的时间有限,过一定的时间就会自动消失,并且也不能被点击。
在appium中,如果想要定位到toast信息,通过appium自带的inspactor或者sdk里面的uiautomator工具发现是定位不到的,没有对应的属性信息,不过好消息是在appiumV1.6.3及之后的版本中支持toast的获取。
1.toast获取
定位toast信息要求
1.uiautomator2只支持安卓俺呢白牛5.0+(模拟器可以使用夜神模拟器)
2.appium server版本1.6.3+以上
3.在desiredcapabilities中指定对应的属性automationName为UIAutomator2
desired_caps = {
'platformName': 'Android',
'platformVersion': '7.0',
'deviceName': 'V889F',
'appPackage': 'com.alibaba.mts.mtsdemoapp',
'appWaitPackage': 'com.alibaba.mts.mtsdemoapp',
'app': 'D:/home/mdp/result/GroovyTest/case1/task.apk',
'newCommandTimeout': 30,
'automationName': 'Appium'
}
desired_caps['automationName']="UIAutomator2"
要求满足之后,接下来我们就可以用代码来获取对应的信息了。
注意:使用presence_of_element_located,而不能使用visibility_of_element_located,在这里它对toast的可见处理并不支持,会直接抛出命令错误无法执行
#获取对应的toast信息
part_str="登录成功"
xpath_lotor='//*[contains(text(),"{0}")]'.formant(part_str)
try:
WebDriverWait(driver,10,1).until(EC.precence
_of_element_located(MobileBy.XPATH,xpath_locator))
print("找到了toast")
except Error as e:
print("toast错过了,报错{0}".format(e))
def is_toast_exist(driver,text,timeout=30,poll_frequency=0.5):
try:
toast_loc = ("xpath", ".//*[contains(@text,'%s')]"%text)
WebDriverWait(driver, timeout,poll_frequency).until(EC.presence_of_element_located(toast_loc))
return True
except:
return False
is_toast_exist(driver,"登录成功")