本文主要介紹如何在使用selenium進行自動化測試的時候模擬各種鼠標操作。
場景描述
在進行自動化測試的時候,我們可能會需要需要進行鼠標操作的場景,比如:
- 測試右擊,查看是否網(wǎng)頁是否屏蔽了右鍵菜單
- 面對滑塊式登錄驗證方式,模擬拖拽
- 模擬前進或后退等鼠標擴展操作
- ……
解決方案
在python
的第三方庫selenium
中已經(jīng)提供了許多現(xiàn)成的鼠標操作方法,包括鼠標能進行的三種操作:點擊、釋放、移動。以及提供了這三種操作常見的組合操作,我們需要查看我們需要的組合操作是否已經(jīng)由selenium
提供,對于沒有現(xiàn)成方法的操作,需要將我們要進行的鼠標操作分解成這些已經(jīng)有現(xiàn)成方法的鼠標操作的組合。
在selenium
中模擬鼠標操作需要依靠ActionChains()
方法,這個方法用來模擬各種外部設(shè)備(虛擬設(shè)備)的操作(比如鍵盤、鼠標、手寫筆、滾輪等等),操作如下:
-
導(dǎo)入AcitionAPI:
from selenium.webdriver.common.action_chains import ActionChains
-
左鍵單擊(點擊后釋放):
ActionChains(web_driver).click(page_element).perform()
-
右鍵單擊:
ActionChains(web_driver).context_click(page_element).perform()
-
左鍵雙擊:
ActionChains(web_driver).double_click(page_element).perform()
-
移動到指定的頁面元素上(懸浮):
ActionChains(web_driver).move_to_element(page_element).perform()
-
后退(擴展鍵):
- 在
selenium 3
的版本中不支持,需要升級到selenium 4
- 版本號通過
print(selenium.__version__)
查看 - 創(chuàng)建組合鍵生成器:
action = ActionBuilder(web_driver)
- 按下后退鍵:
action.pointer_action.pointer_down(MouseButton.BACK)
- 釋放后退鍵:
action.pointer_action.pointer_up(MouseButton.BACK)
- 執(zhí)行組合鍵:
action.perform()
- 在
-
前進(擴展鍵):
- 在
selenium 3
的版本中不支持,需要升級到selenium 4
- 創(chuàng)建組合鍵生成器:
action = ActionBuilder(web_driver)
- 按下前進鍵:
action.pointer_action.pointer_down(MouseButton.FORWARD)
- 釋放前進鍵:
action.pointer_action.pointer_up(MouseButton.FORWARD)
- 執(zhí)行組合鍵:
action.perform()
- 在
-
按下左鍵后不松開:
ActionChains(web_driver).click_and_hold(page_element).perform()
-
移動指定距離:
ActionChains(web_driver).move_by_offset(橫向距離, 豎向距離)
-
將指定元素拖拽到目標區(qū)域:
ActionChains(web_driver).drag_and_drop(要拖拽的頁面元素,代表目標區(qū)域的頁面元素).perform()
- 代表目標區(qū)域的元素跟要拖拽的頁面元素一樣通過
find_element
定位
-
拖拽元素移動一定距離:
ActionChains(web_driver).drag_and_drop_by_offset(要拖拽的元素, 橫向移動距離, 豎向移動距離).perform()
-
鼠標中鍵點擊:
- 創(chuàng)建組合鍵生成器:
action = ActionBuilder(web_driver)
- 按下中鍵:
action.pointer_action.pointer_down(MouseButton.MIDDLE)
- 釋放中鍵:
action.pointer_action.pointer_up(MouseButton.MIDDLE)
- 執(zhí)行組合鍵:
action.perform()
- 創(chuàng)建組合鍵生成器:
具體代碼
我們以如下滑塊驗證為例:
假設(shè)滑塊的id為slide-1
,則可以用如下代碼將滑塊按住后往左移動300,使得通過驗證:
from selenium.webdriver.common.action_chains import ActionChains
slide = web_driver.find_element_by_id("slide-1") # selenium 3.x.x 的寫法
slide = web_driver.find_element("id", "slide-1") # selenium 4.x.x 的寫法
ActionChains(web_driver).drag_and_drop_by_offset(slide, 300, 0).perform()
滑動完成后效果如下:
如果要處理的滑塊驗證在iframe
標簽中,記得先定位并切換到iframe元素中,然后再進行操作。快去試試吧~
好書推薦:
- 流暢的python
- Python編程 從入門到實踐 第2版
- Python數(shù)據(jù)結(jié)構(gòu)與算法分析 第2版
好課推薦:文章來源:http://www.zghlxwxcb.cn/news/detail-403332.html
- 零基礎(chǔ)學python
- python核心技術(shù)與實戰(zhàn)
- python自動化辦公實戰(zhàn)
寫文不易,如果對你有幫助的話,來一波點贊、收藏、關(guān)注吧~??文章來源地址http://www.zghlxwxcb.cn/news/detail-403332.html
到了這里,關(guān)于「Python|Selenium|場景案例」如何模擬鼠標單擊、雙擊、右擊、長按和拖拽等操作?的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!