最近做移動端H5頁面的自動化測試時候,需要模擬一些上拉,下滑的操作,最初考慮使用使用selenium ActionChains來模擬操作,但是ActionChains 只是針對PC端程序鼠標模擬的一系列操作對H5頁面操作時無效的,
比如:
# 將頁面滾動條拖到底部,需要設置sleep(1)
sleep(1)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# driver.execute_script("window.scrollTo(0, 10000);")
# sleep(3)
后來閱讀了下selenium的文檔發(fā)現TouchAction可以對移動端頁面自動化操作;
首先使用TouchAction的時候首先需要在頭上引入該模塊
from selenium.webdriver.common.touch_actions import TouchActions
通過scroll_from_element、flick_element 方法來實現下拉操作
TouchAction提供的一些方法:
- double_tap(on_element) #雙擊
- flick_element(on_element, xoffset, yoffset, speed) #從元素開始以指定的速度移動
- long_press(on_element) #長按不釋放
- move(xcoord, ycoord) #移動到指定的位置
- perform() #執(zhí)行鏈中的所有動作
- release(xcoord, ycoord) #在某個位置松開操作
- scroll(xoffset, yoffset) #滾動到某個位置
- scroll_from_element(on_element, xoffset, yoffset) #從某元素開始滾動到某個位置
- tap(on_element) #單擊
- tap_and_hold(xcoord, ycoord) #某點按住
因為我們模擬的是移動端的H5自動化測試,首先需要我們將瀏覽器設置成為手機瀏覽器(設置之后,模擬會更加真實)
1.以元素為起點向下滑動,實現下拉操作
scroll_from_element(on_element xoffset yoffset)
on_element:開始元素滾動。
xoffset:X偏移量。
yoffset:Y偏移量。
注意:向下滑動為負數,向上滑動為正數
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()
2.以元素為起點用一定速度向下滑動,實現下拉操作
flick_element(on_element, xoffset, yoffset, speed);
on_element #操作元素定位
xoffset #x軸偏移量
yoffset #y軸偏移量
speed #速度
注意:向上滑動為負數,向下滑動為正數
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()
參考:
[python selenium TouchAction模擬移動端觸摸操作]: https://www.cnblogs.com/mengyu/p/8136421.html
[ python+selenium滑動式驗證碼解決辦法 ]: https://blog.csdn.net/zha6476003/article/details/79002430
[ python selenium 下拉列表定位 ]:https://blog.csdn.net/xm_csdn/article/details/53376839