
本文节选自霍格沃兹测试学院内部教材
工作中我们经常需要对应用的页面进行手势操作,比如滑动、长按、拖动等,AppiumDriver 为我们提供一个模拟手势操作的辅助类 TouchAction,可以通过它对手机屏幕进行手势操作。
具体用法参见链接:https://ceshiren.com/t/topic/3275
from appium.webdriver.common.touch_action import TouchAction
TouchAction 提供的常用的手势操作有如下操作:
Press 按下
release 释放
move_to 移动
tap 点击
longPress 长按
wait 等待
cancel 取消
perform 执行
press
TouchAction 提供的 press( ) 方法可以实现对元素或者坐标的按下操作。通常会结合 release( ) 方法实现对某个元素的点击(包括按下和抬起两个动作)。
在某个控件上执行 press 操作,用法如下:
press(WebElement el)
press(int x, int y)
release
释放操作,可以结合其它的事件使用。代表该系列动作的一个结束标志。在某个控件上执行释放操作,用法如下:
release(WebElement el)
release()
move_to
以控件为目标,从一个点移动到该目标上,用法如下:
move_to(WebElement el)
move_to(WebElement el, int x, int y)
tap
在某个控件的中心点上点击一下,用法如下:
tap(WebElement el)
tap(int x, int y)
tap(WebElement el, int x, int y)
longpress
长按某一控件,用法如下:
long_press(WebElement el)
long_press(int x, int y)
在控件的左上角的 x 坐标偏移 x 单位,y 左边偏移 y 单位的坐标上长按。用法如下:
long_press(WebElement el, int x, int y)
wait
等待,单位为毫秒。可以在操作事件的过程中,短暂的停留几秒再继续操作。用法如下:
wait(long timeout)
cancel
可以取消执行事件链中的事件,用法如下:
cancel()
perform
执行事件链中的事件,一般最后会调用这个方法,顺序执行事件链中的动作。用法如下:
perform()
打开测试应用,从元素 “Views” 文本滑动到 “Accessibility” 元素,创建一个测试文件 test_touchaction.py
,代码如下:
测试 app 官方下载地址:https://github.com/appium/appium/tree/master/sample-code/apps
#!/usr/bin/env python# -*- coding: utf-8 -*-from appium import webdriverfrom appium.webdriver.common.touch_action import TouchActionclass TestTouchAction():def setup(self):caps = {}caps['platformName'] = 'Android'caps['platformVersion'] = '6.0'caps['deviceName'] = 'emulator-5554'caps['appPackage'] = 'io.appium.android.apis'caps['appActivity'] = 'io.appium.android.apis.ApiDemos'self.driver = webdriver.Remote(\"http://127.0.0.1:4723/wd/hub", caps)self.driver.implicitly_wait(5)def teardown(self):self.driver.quit()def test_touchaction_unlock(self):# 点击 Viewsel1 = self.driver.find_element_by_accessibility_id("Views")# 点击 Accessibilityel2 = self.driver.find_element_by_accessibility_id("Accessibility")# TouchAction 滑动操作action = TouchAction(self.driver)action.press(el1).wait(100).move_to\(el2).wait(100).release().perform()
上面代码可以看出,首先定位两个元素 el1 与 el2 ,分别作为滑动过程中起点元素和终点元素,将我们滑动的起点元素与终点元素找到之后,创建一个 TouchAction 对象,调用里面的 press( ) 方法实现起点元素的点击,使用 wait( ) 方法在事件之间添加等待,使用 move_to( ) 方法完成手势的移动操作,然后调用 release( ) 方法来完成手势的抬起,最后调用 perform( ) 方法对添加到 TouchAction 中的事件链顺序执行。
推荐学习
内容全面升级,4 个月 20+ 项目实战强化训练,资深测试架构师、开源项目作者亲授 BAT 大厂前沿最佳实践,带你一站式掌握测试开发必备核心技能(对标阿里P6+,年薪50W+)!直推 BAT 名企测试经理,普遍涨薪 50%+!

⬇️ 点击“阅读原文”,提升测试核心竞争力!





