作者寄語:Don't worry, be happy!
1、什么是action_chains?
ActionChains 是一種底層互動的方式,例如移動滑鼠、點擊左鍵、右鍵、拖曳、鍵盤敲擊等等;通過這些函式方法,可以進行組合已達到更加負責的操作,
2、__init__(driver)
初始化ActionChains,即創建ActionChains對應,
from selenium import webdriver
from selenium.webdriver import ActionChains
chrome_driver = webdriver.Chrome('"D:\\material\\selenium\\web_driver\\chromedriver.exe"') # WebDriver物件
action_chains = ActionChains(chrome_driver) # 創建action_chains物件
3、perform()
當用戶呼叫ActionChains方法執行動作時,這些動作會被存盤到一個ActionChains物件的佇列中,此時并不會真正執行這些動作,
而當呼叫perform()時,ActionChains物件中動作佇列會被一一執行,
action_chains.move_to_element(ele) # 移動滑鼠到指定元素
action_chains.click(ele) # 點擊此元素
# 執行perform前,將移動滑鼠和點擊這兩個個動作存盤在action_chains物件中,但是并未執行這兩個動作
action_chains.perform() # perform執行action_chains物件存盤的動作
如果僅執行一個動作,也可使用匿名函式寫法,
ActionChains(chrome_driver).move_to_element(ele).perform() # 移動滑鼠到指定元素
4、reset_actions()
清空ActionChains物件中原存盤的所有動作,
action_chains.move_to_element(ele) # 移動滑鼠到指定元素
action_chains.click(ele) # 點擊此元素
action_chains.reset_actions() # 清空上述兩個動作
5、click(on_element)
點擊滑鼠左鍵動作,如果on_element不存在此元素,將點擊當前滑鼠位置,
ActionChains(chrome_driver).click(ele).perform() # 點擊此元素并執行
6、click_and_hold(on_element)
按住滑鼠左鍵(保持按住,沒有松開左鍵)動作,如果on_element不存在此元素,將點擊當前滑鼠位置,通常與release(松開按鍵動作)一起使用
ActionChains(chrome_driver).click_and_hold(signin_btn_ele).perform() # 按住sign in按鈕

7、context_click(on_element)
點擊滑鼠右鍵動作,如果on_element不存在此元素,將點擊當前滑鼠位置,
ActionChains(chrome_driver).context_click(signin_btn_ele).perform() # 滑鼠右鍵點擊sign in按鈕

8、double_click(on_element)
雙擊滑鼠左鍵動作,如果on_element不存在此元素,將點擊當前滑鼠位置,
ActionChains(chrome_driver).double_click(signin_btn_ele).perform() # 雙擊滑鼠左鍵點擊sign in按鈕
9、drag_and_drop(source, target)
拖曳滑鼠左鍵動作,將想要拖曳的元素(source)拖曳到目標元素位置(target)
ActionChains(chrome_driver).drag_and_drop(source_ele, target_ele).perform()
或者執行兩步也可實作
action_chains.click_and_hold(source_ele) # 按住滑鼠左鍵
action_chains.release(target_ele) # 釋放按住的滑鼠左鍵
action_chains.perform()
10、key_down(value, element)
按住鍵盤按鍵(不包含松開)動作,通常與key_up(松開按鍵動作)一起使用,
ActionChains(chrome_driver).key_down(Keys.CONTROL,text_ele).send_keys('a').key_up(Keys.CONTROL).perform() # 選中全部text_ele元素文字 Ctrl+A組合鍵
11、key_up(value, element)
松開鍵盤按鍵動作,通常與key_down(按住鍵盤按鍵動作)一起使用
12、move_to_element(to_element)
移動滑鼠到指定元素中間位置上,
ActionChains(chrome_driver).move_to_element(ele).perform() # 移動滑鼠到指定元素
13、pause(seconds)
暫停所有操作xx秒,
action_chains.move_to_element(ele) # 移動滑鼠到指定元素
action_chains.pause(3) # 暫停3秒
action_chains.click(ele) # 點擊此元素
action_chains.perform() # 執行上述兩個動作
14、release(on_element)
松開滑鼠按鍵動作,如果on_element沒有此元素,則松開滑鼠按鍵當前位置的元素
見#6、click_and_hold(on_element)
15、send_keys(*keys_to_send)
發送按鍵到當前焦點所在的元素上,
見#10、key_down(value, element)
16、send_keys_to_element(element, *keys_to_send)
發送按鍵到指定元素上,
見#10、key_down(value, element)
總結:
Selenium action_chains 的用途非常廣泛,屬于底層操作的一種,
學習Selenium自動化測驗必須掌握的技巧之一,
******本文屬于原創作品,轉載請注明出處******
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/287547.html
標籤:其他
下一篇:列舉類
