Python+Appium自动化测试(13)-toast定位

简介: 在app自动化测试的过程中经常会遇到需要对toast进行定位,最常见的就是定位toast或者获取toast的文案进行断言,如下图,通过定位"登录成功"的toast就可以断言今日头条登录用例是否通过。但toast区别于控件元素,无法获取焦点,不能通过uiautomatorviewer.bat、appium、weditor等工具定位,因此我们就需要通过别的方法来定位。

一,前言


在app自动化测试的过程中经常会遇到需要对toast进行定位,最常见的就是定位toast或者获取toast的文案进行断言,如下图,通过定位"登录成功"的toast就可以断言今日头条登录用例是否通过。但toast区别于控件元素,无法获取焦点,不能通过uiautomatorviewer.bat、appium、weditor等工具定位,因此我们就需要通过别的方法来定位。

微信图片_20220424161803.png


二,环境


  • windows 10
  • Android 10
  • appium 1.18.0 (desktop)
  • selenium 3.141.0
  • jdk 1.8


三,toast定位准备与定位方法


1,准备

注意:网上大量的博客都说定位toast需要使用uiautomator2,且需要安装appium-uiautomator2-driver。但我在以上环境定位toast时是不需要uiautomator2,也无需安装appium-uiautomator2-driver,且能定位成功!!!大家可以尝试,如果报错的话就老实按照下面步骤进行吧。


1.1,在Capablity里新增参数使用uiautomator2:

desired_caps['automationName'] = 'uiautomator2',


1.2,再安装appium-uiautomator2-driver,命令如下:

cnpm install appium-uiautomator2-driver

安装成功后在C:\Users\xxx\node_modules会出现如下文件:

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


2,定位方法

toast需使用xpath的方式进行定位


2.1,根据toast的文本内容定位toast


driver.find_element_by_xpath('//*[@text="xxxxxx"]')

这种方式一般用于判断或断言是否出现文本为"xxxxxx"的toast,因此我们可以封装如下:

# -*- coding:utf-8 -*-
# @author: 给你一页白纸
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait
from appium.webdriver.common.mobileby import MobileBy as By
def is_toast_exist(driver, text, timeout=20, poll_frequency=0.1):
    '''
    判断toast是否存在,是则返回True,否则返回False
    :param driver: driver实例对象
    :param text: toast文本
    :param timeout: 定位超时时间
    :param poll_frequency: 查询频率
    :return: True or False
    '''
    try:
        toast_loc = (By.XPATH, ".//*[contains(@text, %s)]" % text)
        WebDriverWait(driver, timeout, poll_frequency).until(
            ec.presence_of_element_located(toast_loc)
        )
        return True
    except:
        return False


2.2,根据toast的属性className定位toast


toast的className值为:android.widget.Toast

driver.find_element_by_xpath('//*[@class="android.widget.Toast"]')

这种方式一般用于获取toast的文本内容,封装如下:

# -*- coding:utf-8 -*-
# @author: 给你一页白纸
def get_toast_text(driver, timeout=20, poll_frequency=0.1):
    '''
    定位toast元素,获取text属性
    :param driver: driver实例对象
    :param timeout: 元素定位超时时间
    :param poll_frequency: 查询频率
    :return: toast文本内容
    '''
    toast_loc = (By.XPATH, '//*[@class="android.widget.Toast"]')
    try:
        toast = WebDriverWait(driver, timeout, poll_frequency).until(
            ec.presence_of_element_located(toast_loc)
        )
        toast_text = toast.get_attribute('text')
        return toast_text
    except Exception as e:
        return e


注意

  • 等待方式只能用presence_of_element_located(),即只能等待其存在,而不能等待其可见。
  • 如果初始化构造driver时已经使用了隐式等待implicitly_wait(),则timeout参数可以不写。


四,示例代码


定位今日头条app账号密码登录成功后的 "登录成功"toast

注意:我这里是将desired_caps里的Uiautomator2参数注释掉了,且未安装appium-uiautomator2-driver,也同样能定位到,大家可在与我相同的环境下进行尝试。

# -*- coding:utf-8 -*-
# @author: 给你一页白纸
from appium import webdriver
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait
from appium.webdriver.common.mobileby import MobileBy as By
def android_driver():
    desired_caps = {
        "platformName": "Android",
        "platformVersion": "10",
        "deviceName": "PCT_AL10",
        "appPackage": "com.ss.android.article.news",
        "appActivity": ".activity.MainActivity",
        # "automationName": "UiAutomator2",
        "unicodeKeyboard": True,
        "resetKeyboard": True,
        "noReset": True,
    }
    # 启动app
    driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
    return driver
def is_toast_exist(driver, text, timeout=20, poll_frequency=0.1):
    '''
    判断toast是否存在,是则返回True,否则返回False
    '''
    try:
        toast_loc = (By.XPATH, ".//*[contains(@text, %s)]" % text)
        WebDriverWait(driver, timeout, poll_frequency).until(
            ec.presence_of_element_located(toast_loc)
        )
        return True
    except:
        return False
def get_toast_text(driver, timeout=20, poll_frequency=0.1):
    '''
    定位toast元素,获取text属性
    '''
    toast_loc = (By.XPATH, '//*[@class="android.widget.Toast"]')
    try:
        toast = WebDriverWait(driver, timeout, poll_frequency).until(
            ec.presence_of_element_located(toast_loc)
        )
        toast_text = toast.get_attribute('text')
        return toast_text
    except Exception as e:
        return e
def login_opera(driver):
    '''登录今日头条操作'''
    try:
        # driver.find_element_by_id("com.ss.android.article.news:id/cji").click()  # 点击【同意】
        driver.find_element_by_id("com.ss.android.article.news:id/cji").click() # 点击【我知道了】
        driver.find_element_by_id("android:id/button1").click() # 点击权限管理-确定按钮
        driver.find_element_by_xpath("//android.widget.TabWidget/android.widget.RelativeLayout[@index=3]").click() # 点击未登录
        driver.find_element_by_id("com.ss.android.article.news:id/a10").click() # 未登录页点击登录按钮
        driver.find_element_by_id("com.ss.android.article.news:id/bgh").click() # 登录页点击“。。。”
        driver.find_element_by_xpath("//android.widget.LinearLayout[@index=4]").click() # 选择密码登录
        driver.find_element_by_id("com.ss.android.article.news:id/bu").send_keys("xxxxxxxx")   # 输入账号
        driver.find_element_by_id("com.ss.android.article.news:id/c5").send_keys("xxxxxxxx")   # 输入密码
        driver.find_element_by_id("com.ss.android.article.news:id/a2o").click() # 点击登录
    except Exception as e:
        print("登录错误,原因为:{}".format(e))
        # 报错时截图
        driver.get_screenshot_as_file(r'E:\blog\blog_script\images\test_login_error_01.png')
    else:
        toast_text = get_toast_text(driver)
        print(toast_text)
        toast_el = is_toast_exist(driver, "登录成功")
        print(toast_el)
if __name__ == '__main__':
    driver = android_driver()
    login_opera(driver)

运行结果如下,说明定位该toast成功:

C:\Users\xiaoqq\AppData\Local\Programs\Python\Python37\python.exe E:/blog/blog_script/login_jrtt.py
登录成功
True
Process finished with exit code 0
相关文章
|
2月前
|
搜索推荐 Python
使用Python自动化生成物业通知单
本文介绍如何使用Python结合Pandas和python-docx库自动化生成物业通知单。通过读取Excel数据并填充至Word模板,实现高效准确的通知单批量制作。包括环境准备、代码解析及效果展示,适用于物业管理场景。
91 14
|
2月前
|
Python
自动化微信朋友圈:Python脚本实现自动发布动态
本文介绍如何使用Python脚本自动化发布微信朋友圈动态,节省手动输入的时间。主要依赖`pyautogui`、`time`、`pyperclip`等库,通过模拟鼠标和键盘操作实现自动发布。代码涵盖打开微信、定位朋友圈、准备输入框、模拟打字等功能。虽然该方法能提高效率,但需注意可能违反微信使用条款,存在风险。定期更新脚本以适应微信界面变化也很重要。
234 61
|
2天前
|
存储 数据采集 数据格式
Python自动化Office文档处理全攻略
本文介绍如何使用Python自动化处理Word、Excel和PDF文档,提升办公效率。通过安装`python-docx`、`openpyxl`、`pandas`、`PyPDF2`和`pdfplumber`等库,可以轻松实现读取、修改、创建和批量处理这些文档。具体包括:自动化处理Word文档(如读取、修改内容、调整样式),Excel文档(如读取、清洗、汇总数据),以及PDF文档(如提取文本和表格数据)。结合代码示例和实战案例,帮助你掌握高效办公技巧,减少手动操作的错误率。
14 1
|
1月前
|
机器学习/深度学习 运维 数据可视化
Python时间序列分析:使用TSFresh进行自动化特征提取
TSFresh 是一个专门用于时间序列数据特征自动提取的框架,支持分类、回归和异常检测等机器学习任务。它通过自动化特征工程流程,处理数百个统计特征(如均值、方差、自相关性等),并通过假设检验筛选显著特征,提升分析效率。TSFresh 支持单变量和多变量时间序列数据,能够与 scikit-learn 等库无缝集成,适用于大规模时间序列数据的特征提取与模型训练。其工作流程包括数据格式转换、特征提取和选择,并提供可视化工具帮助理解特征分布及与目标变量的关系。
83 16
Python时间序列分析:使用TSFresh进行自动化特征提取
|
1月前
|
存储 安全 数据可视化
用Python实现简单的任务自动化
本文介绍如何使用Python实现任务自动化,提高效率和准确性。通过三个实用案例展示:1. 使用`smtplib`和`schedule`库自动发送邮件提醒;2. 利用`shutil`和`os`库自动备份文件;3. 借助`requests`库自动下载网页内容。每个案例包含详细代码和解释,并附带注意事项。掌握这些技能有助于个人和企业优化流程、节约成本。
76 3
|
2月前
|
JSON 数据可视化 测试技术
python+requests接口自动化框架的实现
通过以上步骤,我们构建了一个基本的Python+Requests接口自动化测试框架。这个框架具有良好的扩展性,可以根据实际需求进行功能扩展和优化。它不仅能提高测试效率,还能保证接口的稳定性和可靠性,为软件质量提供有力保障。
118 7
|
2月前
|
敏捷开发 测试技术 持续交付
自动化测试之美:从零开始搭建你的Python测试框架
在软件开发的马拉松赛道上,自动化测试是那个能让你保持节奏、避免跌宕起伏的神奇小助手。本文将带你走进自动化测试的世界,用Python这把钥匙,解锁高效、可靠的测试框架之门。你将学会如何步步为营,构建属于自己的测试庇护所,让代码质量成为晨跑时清新的空气,而不是雾霾中的忧虑。让我们一起摆脱手动测试的繁琐枷锁,拥抱自动化带来的自由吧!
|
JavaScript Java 测试技术
App自动化测试|Appium+Python自动化测试环境搭建(Windows)
App自动化测试|Appium+Python自动化测试环境搭建(Windows)
App自动化测试|Appium+Python自动化测试环境搭建(Windows)
|
Web App开发 iOS开发 Python
Appium+python自动化16-appium1.6在mac上环境搭建启动ios模拟器上Safari浏览器
前言 在mac上搭建appium踩了不少坑,先是版本低了,启动后无限重启模拟器。后来全部升级最新版本,就稳稳的了。 环境准备: 1.OS版本号10.12 2.xcode版本号8.3.2 3.appium版本号1.
2534 0
|
Python
Appium+python自动化15-在Mac上环境搭建
前言 mac上搭建appium+python的环境还是有点复杂的,需要准备的软件 1.nodejs 2.npm 3.cnpm 4.appium 5.pip 6.Appium-Python-Client   一、nodejs安装 1.
1811 0

热门文章

最新文章