Android中的Toast是一種簡易的消息提示框,當視圖顯示給用戶,在應用程序中顯示爲浮動,和Dialog不同的是,它永遠不會得到焦點,沒法被點擊android
Toast類的思想就是儘量不引人注意,同時還向用戶顯示信息,但願他們看到,並且Toast顯示的時間有限,通常3秒左右就消失了,所以使用傳統的元素定位方式,是沒法定位到Toast元素的web
Appium1.6.3開始支持識別Toast內容,主要是基於uiAutomator2,所以須要在Capability配置以下參數npm
desired_caps['automationName']='uiautomator2'app
安裝appium-uiautomator2-driver安裝命令以下ui
cnpm install appium-uiautomator2-driverspa
安裝好後在對應目錄下能夠看到對應的文件code
import pytest from appium import webdriver from selenium.webdriver.support.ui import WebDriverWait class Testcsca(): def setup(self): caps = {} caps["platformName"] = "Android" # caps["deviceName"] = "127.0.0.1:62001" caps["deviceName"] = "CLB0219314000452" caps["appPackage"] = "com.jgw.csca" caps["appActivity"] = "com.jgw.csca.view.activity.LoginActivity" caps["platfromVersion"] = "9.0.0" caps["autoGrantPermissions"] = True # 設置自動受權權限 caps['unicodeKeyboard'] = True # 輸入中文時要加,要否則輸入不了中文 caps['resetKeyboard'] = True # 輸入中文時要加,要否則輸入不了中文 caps['automationName'] = 'uiautomator2' self.driver = webdriver.Remote("http://localhost:4723/wd/hub", caps) self.driver.implicitly_wait(20) def test_login(self): self.driver.find_element_by_android_uiautomator('new UiSelector().text("請輸入用戶名")').send_keys('www') self.driver.find_element_by_android_uiautomator('new UiSelector().resourceId("com.jgw.csca:id/et_pwd")').send_keys('balabala') self.driver.find_element_by_android_uiautomator('new UiSelector().className("android.widget.Button")').click() message = "用戶密碼錯誤" # 設置toast的錯誤信息 element_message = '//*[@text=\'{message}\']'.format(message=message) # 拼接成xpath的格式 print('message:', element_message) toast_element = WebDriverWait(self.driver, 5).until(lambda x: x.find_element_by_xpath(element_message)) print('toast:',toast_element.text)
結果:orm
message: //*[@text='用戶密碼錯誤'] toast: 用戶密碼錯誤