Action Chains類經常使用於模擬鼠標的行爲,好比單擊,雙擊,拖拽等行爲,使用下面的方法導入Action Chains類css
from selenium.webdriver.common.action_chains import ActionChains
下面先來看一個例子:html
import time from selenium import webdriver from selenium.webdriver import ActionChains browser =webdriver.Firefox() browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable') browser.switch_to.frame('iframeResult') # id = 'iframeResult' source = browser.find_element_by_css_selector('#draggable') # 被拖拽的對象 target = browser.find_element_by_css_selector('#droppable') # 目標對象 actions = ActionChains(browser) actions.drag_and_drop(source, target) actions.perform() time.sleep(3) browser.close()
以上的例子中,實現了鼠標的拖拽操做,首先須要實例化,而後調用其中的方法,完成相應的操做。jquery
下面是一些經常使用的模擬鼠標的操做web
- click(on_element=None)
鼠標單擊 - click_and_hold(on_element=None)
鼠標單擊而且按住不放 - context_click(on_element=None)
右擊 - double_click(on_element=None)
雙擊 - drag_and_drop(source, target)
拖拽 - drag_and_drop_by_offset(source, xoffset, yoffset)
將目標拖動到指定的位置 -
key_down(value, element=None)
按住某個鍵,使用這個方法能夠方便的實現某些快捷鍵,好比下面按下Ctrl+c鍵apiActionsChains(browser).key_down(Keys.CONTROL).send_keys('c').perform()
-
key_up(value, element=None)
鬆開某個鍵,能夠配合上面的方法實現按下Ctrl+c而且釋放。markdownActionsChains(browser).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
- move_by_offset(xoffset, yoffset)
指定鼠標移動到某一個位置,須要給出兩個座標位置 - move_to_element(to_element)
將鼠標移動到指定的某個元素的位置 - move_to_element_with_offset(to_element, xoffset, yoffset)
移動鼠標到某個元素位置的偏移位置 - perform()
將以前的一系列的ActionChains執行 - release(on_element=None)
釋放按下的鼠標 - send_keys(*keys_to_send)
向某個元素位置輸入值 -
send_keys_to_element(element, *keys_to_send)
向指定的元素輸入數據less