appium--Toast元素识别

前戏

Android中的Toast是一种简易的消息提示框,当视图显示给用户,在应用程序中显示为浮动,和Dialog不一样的是,它永远不会获得焦点,无法被点击

Toast类的思想就是尽可能不引人注意,同时还向用户显示信息,希望他们看到,而且Toast显示的时间有限,一般3秒左右就消失了,因此使用传统的元素定位方式,是无法定位到Toast元素的

Appium1.6.3开始支持识别Toast内容,主要是基于uiAutomator2,因此需要在Capability配置如下参数

desired_caps['automationName']='uiautomator2'

安装appium-uiautomator2-driver安装命令如下

cnpm install appium-uiautomator2-driver

安装好后在对应目录下可以看到对应的文件

复制代码
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)
复制代码

结果:

message: //*[@text='用户密码错误']
toast: 用户密码错误

 

posted @   邹邹很busy。  阅读(656)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示

目录导航