一、前置说明
toast消失的很快,并且通过uiautomatorviewer也不能获取到它的定位信息,如下图:
二、操作步骤
toast的class name值为android.widget.Toast
,虽然toast消失的很快,但是它终究是在Dom结构中出现过,所以我们可以使用xpath来定位toast元素:
def get_toast(self, text=None, timeout=3, interval=0.5):# 如果同时出现多个toast,可以使用这种方式if text:return WebDriverWait(self, timeout, interval).until(EC.presence_of_element_located(('xpath', f'//*[contains(@text, "{text}")]')))return WebDriverWait(self, timeout, interval).until(EC.presence_of_element_located(('xpath', '//*[@class="android.widget.Toast"]')))
三、Demo验证
注意:appium在v1.6.3以上才支持获取toast,并且需要指定使用Uiautomator2库。
def test_get_toast():import logginglogging.basicConfig(level=logging.DEBUG)from driver.appium.driver import WebDriverappium_server_url = 'http://localhost:4723'capabilities = {"platformName": "Android","automationName": "uiautomator2", # 注意:要指定uiautomator2"deviceName": "127.0.0.1:62001","app": "D:\\resources\\ApiDemos-debug.apk",}driver = WebDriver(command_executor=appium_server_url, capabilities=capabilities)driver.smart_find_element(by='text', value='App').click()driver.smart_find_element(by='text', value='Notification').click()driver.smart_find_element(by='text', value='NotifyWithText').click()driver.smart_find_element(by='text', value='SHOW SHORT NOTIFICATION').click()element = driver.get_toast('Short notification')assert element.text == 'Short notification'
日志输出:
============================= test session starts =============================
collecting ... collected 1 itemtest_appium.py::test_get_toast PASSED============================= 1 passed in 19.91s ==============================
欢迎技术交流: