最近作移动端H5页面的自动化测试时候,须要模拟一些上拉,下滑的操做,最初考虑使用使用selenium ActionChains来模拟操做,可是ActionChains 只是针对PC端程序鼠标模拟的一系列操做对H5页面操做时无效的,后来阅读了下selenium的文档发现TouchAction能够对移动端页面自动化操做;html
首先使用TouchAction的时候首先须要在头上引入该模块python
from selenium.webdriver.common.touch_actions import TouchActions
经过scroll_from_element、flick_element 方法来实现下拉操做web
由于咱们模拟的是移动端的H5自动化测试,首先须要咱们将浏览器设置成为手机浏览器;chrome
1.以元素为起点以必定速度向下滑动,实现下拉操做浏览器
注意:测试
向上滑动为负数,向下滑动为正数spa
# -*- coding: utf-8 -*- # @Time : 2017/12/28 10:26 # @Author : Hunk # @File : ex86.py.py # @Software: PyCharm import time from selenium import webdriver from selenium.webdriver.common.touch_actions import TouchActions """设置手机的大小""" mobileEmulation = {'deviceName': 'Apple iPhone 5'} options = webdriver.ChromeOptions() options.add_experimental_option('mobileEmulation', mobileEmulation) driver = webdriver.Chrome(chrome_options=options) driver.get('http://m.test.90dichan.com') driver.maximize_window() """定位操做元素""" button = driver.find_element_by_xpath('//*[@id="pullrefresh"]/div[2]/ul/li[2]/a/div[2]/span') time.sleep(3) Action = TouchActions(driver) """从button元素像下滑动200元素,以50的速度向下滑动""" Action.flick_element(button, 0, 200, 50).perform() time.sleep(3) driver.close()
2.以元素为起点向下滑动,实现下拉操做code
注意:orm
向下滑动为负数,向上滑动为正数htm
# -*- coding: utf-8 -*- # @Time : 2017/12/28 10:26 # @Author : Hunk # @File : ex86.py.py # @Software: PyCharm import time from selenium import webdriver from selenium.webdriver.common.touch_actions import TouchActions """设置手机的大小""" mobileEmulation = {'deviceName': 'Apple iPhone 5'} options = webdriver.ChromeOptions() options.add_experimental_option('mobileEmulation', mobileEmulation) driver = webdriver.Chrome(chrome_options=options) driver.get('http://m.test.90dichan.com') driver.maximize_window() """定位操做元素""" button = driver.find_element_by_xpath('//*[@id="pullrefresh"]/div[2]/ul/li[2]/a/div[2]/span') time.sleep(3) Action = TouchActions(driver) """从button元素像下滑动200元素""" Action.scroll_from_element(button, 0, -200).perform() time.sleep(3) driver.close()
下面咱们看下下拉的效果
下面看一下TouchAction提供的其余那些方法:
其实上述的部分方法与ActionChains 中的鼠标操做很类似,因为与鼠标操做的书写方法一致的,因此在这里不详细介绍,具体书写方法你们能够参考下【python selenium-webdriver 元素操做之鼠标操做(四)】内容,下面咱们主要来介绍下移动的操做。