Android中的Toast是一種簡易的消息提示框。且一般顯示3s左右的時間就消失。他屬於系統的一種提示,而不是應用上的。所以使用定位元素工具定位是獲取不到Toast元素的。
定位Toast元素需要借助UiAutomator2 ,automationName:uiautomator2;由於他的設計方式,所以在getPageSource 是查找不到的。在定位Toast元素時必須使用xpath定位方式。
使用xpath定位有兩種方法,一種是借助Toast的className:android.widget.Toast;另一種是借助文本內容。所以定位寫法有兩種形式:
driver.find_element_by_xpath("//*[@class='android.widget.Toast']")
driver.find_element_by_xpath("//*[@text='xxxxx']")
在app UI自動化中,Toast是常用的一種文言提示方法。所以對此進行封裝,便於以后調用。
# coding:utf-8 from appium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def get_toast(driver, text=None, timeout=5, poll_frequency=0.5): """ get toast :param driver: driver :param text: toast text :param timeout: Number of seconds before timing out, By default, it is 5 second. :param poll_frequency: sleep interval between calls, By default, it is 0.5 second. :return: toast """ if text: toast_loc = ("//*[contains(@text, '%s')]" %text) else: toast_loc = "//*[@class='android.widget.Toast']" try: WebDriverWait(driver, timeout, poll_frequency).until(EC.presence_of_element_located(('xpath', toast_loc))) toast_elm = driver.find_element_by_xpath(toast_loc) return toast_elm except: return "Toast not found"
解釋:WebDriverWait(driver, timeout, poll_frequency).until(EC.presence_of_element_located(('xpath', toast_loc)))
在這只是相當於一個頻率執行,在固定的時間中判斷Toast是否存在。當然,如果在初始化driver時設置了driver.implicitly_wait(30),則這兒的查找可以注釋掉。
在這兒這樣設計的目的只是為了避免代碼執行太快或太慢,獲取不到Toast,增強代碼的健壯性而已
調用也很簡單,如果是需要判斷Toast是否出現,則只需要判斷 get_toast()為True。
如果要獲取Toast文本,則添加 text,get_toast().text