TouchAction
在之前说过了滑动swip,那种是两点之间的滑动,比如上滑,左滑等。但实际工作中会遇到一些复杂的场景,如九宫格的滑动等待,这时候就要使用TouchAction,TouchAction包含一系列操作,比如按压,长按,点击,移动,暂停,使用TouchAction需要先导入对应的模块
from appium.webdriver.common.touch_action import
按压
方法:press()开始按压一个元素或者坐标点(x,y),通过手指按压手机屏幕的某个位置,press()也可以接收屏幕的坐标(x,y)
press(self,el=None,x=None,y=None)
TouchAction(driver).press(x=0,y=300)
TouchAction(driver).press(x=0,y=308).release().perform()
除了press()方法之外,本例中还用到了别外两个新方法。
- release() 结束的行动取消屏幕上的指针。
- Perform() 执行的操作发送到服务器的命令操作
长按
方法:longPress()
开始按压一个元素或坐标点(x,y)。 相比press()方法,longPress()多了一个入参,既然长按,得有按的时间吧。duration以毫秒为单位。1000表示按一秒钟。其用法与press()方法相同。
long_press(self,el=None,x=None,y=None,duration=1000)
点击
方法:tap()
对一个元素或控件执行点击操作。用法参考press()。
tap(self,el=None,x=None,y=None,count=1)
移动
move_to()将指针从上一个点移动到指定的元素或点
move_to(self,el=None,x=None,y=None)
注意:移动到目标位置有时是算绝对路径,有时是基于前面一个坐标点的偏移量,要结合具体的app来实践
暂停
Wait()
wait(self,ms=0)
单位为ms
释放
方法release()结束的行动或取消屏幕上的指针
release(self)
执行
perform()执行的操作发送到服务器的命令操作
perform(self)
实战
目的:完成下面的图案滑动
1 from appium.webdriver.common.touch_action import TouchAction
2 from appium import webdriver
3
4 desired_caps = {}
5 desired_caps['platformName'] = 'Android'
6 desired_caps['deviceName'] = '127.0.0.1:62001'
7 desired_caps['platforVersion'] = '5.1.1'
8 desired_caps['app'] = r'F:\xxx.apk' # 安装app
9 desired_caps['appPackage'] = 'com.xxx'
10 desired_caps['appActivity'] = 'com.bizxxx'
11
12 driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
13
14
15 def get_size():
16 x = driver.get_window_size()['width']
17 y = driver.get_window_size()['height']
18 return x, y
19
20 # 向左滑动
21 def swipeleft():
22 l = get_size()
23 x1 = int(l[0] * 0.9)
24 y1 = int(l[1] * 0.5)
25 x2 = int(l[0] * 0.1)
26 driver.swipe(x1, y1, x2, y1, 1000)
27
28 # 向上滑动
29 def swipeUp():
30 l = get_size()
31 x1 = int(l[0] * 0.5)
32 y1 = int(l[1] * 0.95)
33 y2 = int(l[1] * 0.35)
34 driver.swipe(x1, y1, x1, y2, 1000)
35
36
37 for i in range(2):
38 TouchAction(driver).press(x=262, y=385).wait(2000) \
39 .move_to(x=451, y=388).wait(1000) \
40 .move_to(x=650, y=589).wait(1000) \
41 .move_to(x=649, y=785).wait(1000) \
42
代码解释:
第28行执行滑动操作,press按下了第一个点等待2秒,第39行表示移动到第二个点,等待1秒,第40行表示移动到第三个点,等待1s,第41行表示,移动到第四个点,等待1s,第42行release()表示释放连续滑动操作,perform()表示发送到服务端执行前面的一系列操作