Appium之Toast元素識別

問題思考

在平常使用App過程當中,常常會看到App界面有一些彈窗提示(以下圖所示)這些提示元素出現後等待3秒左右就會自動消失,那麼咱們該如何獲取這些元素文字內容呢?node

 

Toast簡介

Android中的Toast是一種簡易的消息提示框。 當視圖顯示給用戶,在應用程序中顯示爲浮動。和Dialog不同的是,它永遠不會得到焦點,沒法被點擊。python

Toast類的思想就是儘量不引人注意,同時還向用戶顯示信息,但願他們看到。並且Toast顯示的時間有限,通常3秒左右就消失了。所以使用傳統的元素定位工具,咱們是沒法定位到Toast元素的(傳說中低調奢華有內涵)。git

Appium Toast內容獲取

Add ability to verify TOAST messages (these can't be interacted with, only text retrieval allowed)github

Appium 1.6.3開始支持識別Toast內容,主要是基於UiAutomator2,所以須要在Capablity配置以下參數:web

desired_caps['automationName']='uiautomator2'npm

安裝appium-uiautomator2-driver: 安裝命令以下:app

cnpm install appium-uiautomator2-driverxss

安裝成功後能夠在 C:\Users\XXXX\node_modules看到對應的文件:工具

  • _appium-uiautomator2-driver@1.12.0@appium-uiautomator2-driver
  • _appium-uiautomator2-server@1.10.0@appium-uiautomator2-server

 

 

 

安裝selenium模塊測試

pip install selenium

 

安裝完成後使用以下命令檢測是否安裝成功

#查看selenium版本

C:\Users\Shuqing>pip show selenium

Name: selenium

Version: 3.11.0

Summary: Python bindings for Selenium

Home-page: https://github.com/SeleniumHQ/selenium/

Author: UNKNOWN

Author-email: UNKNOWN

License: Apache 2.0

Location: c:\python35\lib\site-packages

Requires:

Required-by: Appium-Python-Client

 

測試環境

  • jdk版本:"1.8.0_05"
  • appium版本:1.7.2 (不能低於1.6.3)
  • selenium:3.11.0
  • 測試設備:Android 5.1.1
  • Python:3.5
  • 測試App:考研幫Android app V3.1.0

測試場景

進入登陸界面輸入錯誤的用戶名或者密碼,獲取Toast內容:

  • 「用戶名或密碼錯誤,你還能夠嘗試4次」
  • 「驗證失敗次數過多,請15分鐘後再試」

代碼實現

get_toast.py

# coding=utf-8

from find_element.capability import driver

from selenium.webdriver.support.ui import WebDriverWait

 

driver.find_element_by_id('com.tal.kaoyan:id/login_email_edittext').clear()

driver.find_element_by_id('com.tal.kaoyan:id/login_email_edittext').send_keys('zxss018')

 

driver.find_element_by_id('com.tal.kaoyan:id/login_password_edittext').send_keys('zxw2018')

driver.find_element_by_id('com.tal.kaoyan:id/login_login_btn').click()

 

 

error_message="用戶名或密碼錯誤,你還能夠嘗試4次"

limit_message="驗證失敗次數過多,請15分鐘後再試"

 

message='//*[@text=\'{}\']'.format(error_message)

# message='//*[@text=\'{}\']'.format(limit_message)

 

toast_element=WebDriverWait(driver,5).until(lambda x:x.find_element_by_xpath(message))

print(toast_element.text)

 

 

注意:Toast內容爲中文時,頂部必須註釋# coding=utf-8 不然會由於編解碼致使文字識別失敗。

 

參考資料

https://testerhome.com/topics/6685

相關文章
相關標籤/搜索