TouchAction
在之前說過了滑動swip,那種是兩點之間的滑動,比如上滑,左滑等。但實際工作中會遇到一些復雜的場景,如九宮格的滑動等待,這時候就要使用TouchAction,TouchAction包含一系列操作,比如按壓,長按,點擊,移動,暫停,使用TouchAction需要先導入對應的模塊
from appium.webdriver.common.touch_action import TouchAction
按壓
方法: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 .release().perform()
代碼解釋:
第28行執行滑動操作,press按下了第一個點等待2秒,第39行表示移動到第二個點,等待1秒,第40行表示移動到第三個點,等待1s,第41行表示,移動到第四個點,等待1s,第42行release()表示釋放連續滑動操作,perform()表示發送到服務端執行前面的一系列操作