一、前置說明
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 ==============================
歡迎技術交流: