Play with python selenium mouse and keyboard (ActionChains)
- 2020-05-10 18:26:39
- OfStack
When automating with selenium, you sometimes encounter situations where you need to simulate mouse operations, such as clicking, double-clicking, right-clicking, drag-and-drop, and so on. selenium gives us a class to handle such events -- ActionChains
selenium.webdriver.common.action_chains.ActionChains(driver)
This class basically meets all of our mouse needs.
1. Basic usage of ActionChains
First of all, you need to understand how ActionChains works. When you call ActionChains's method, it will not be executed immediately, but all the operations will be stored in a queue in order. When you call perform's method, the time in the queue will be executed in sequence.
In this case we can have two call methods:
The & # 8226; The chain of writing
menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")
ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()
& # 8226; Step by step written
menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")
actions = ActionChains(driver)
actions.move_to_element(menu)
actions.click(hidden_submenu)
actions.perform()
Either way, is essentially the same. ActionChains does everything in order.
2. List of ActionChains methods
click(on_element=None) -- click the left mouse button
click_and_hold(on_element=None) -- click the left mouse button and do not release it
context_click(on_element=None) -- right click
double_click(on_element=None) -- double-click the left mouse button
drag_and_drop(source, target) -- drag to an element and release
drag_and_drop_by_offset(source, xoffset, yoffset) -- drag to a coordinate and release
key_down(value, element=None) -- press a key on a keyboard
key_up(value, element=None) -- release a key
move_by_offset(xoffset, yoffset) -- moves the mouse from its current position to a coordinate
move_to_element(to_element) -- move the mouse over an element
move_to_element_with_offset(to_element, xoffset, yoffset) -- move to the distance from an element (upper-left coordinate)
perform() -- execute all actions in the chain
release(on_element=None) -- release the left mouse button at an element location
send_keys(*keys_to_send) -- sends a key to the element in the current focus
send_keys_to_element(element, *keys_to_send) -- sends a key to the specified element
Use the following examples to detail and demonstrate the use of each method:
3. Code examples
1. Click to operate
http sample url: / / sahitest com/demo/clicks htm
Code:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.maximize_window()
driver.get('http://sahitest.com/demo/clicks.htm')
click_btn = driver.find_element_by_xpath('//input[@value="click me"]') # Click the button
doubleclick_btn = driver.find_element_by_xpath('//input[@value="dbl click me"]') # Double click on the button
rightclick_btn = driver.find_element_by_xpath('//input[@value="right click me"]') # Right-click the button
ActionChains(driver).click(click_btn).double_click(doubleclick_btn).context_click(rightclick_btn).perform() # Chain usage
print driver.find_element_by_name('t2').get_attribute('value')
sleep(2)
driver.quit()
Results:
[CLICK][DOUBLE_CLICK][RIGHT_CLICK]
2. Mouse movement
http sample url: / / sahitest com/demo/mouseover htm
Sample code:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.maximize_window()
driver.get('http://sahitest.com/demo/mouseover.htm')
write = driver.find_element_by_xpath('//input[@value="Write on hover"]') # Mouse over this element, below input The box will say" Mouse moved "
blank = driver.find_element_by_xpath('//input[@value="Blank on hover"]') # Moving the mouse over this element empties the bottom input What's in the box
result = driver.find_element_by_name('t1')
action = ActionChains(driver)
action.move_to_element(write).perform() # Move to the write That" Mouse moved "
print result.get_attribute('value')
# action.move_to_element(blank).perform()
action.move_by_offset(10, 50).perform() # Move to current distance (10,50) The point, as in the previous sentence, is moved to blank The empty
print result.get_attribute('value')
action.move_to_element_with_offset(blank, 10, -40).perform() # Move to distance blank The element (10,-40) It can be moved to write on
print result.get_attribute('value')
sleep(2)
driver.quit()
The results of
Mouse moved
Mouse moved
3. Drag and drop
http sample url: / / sahitest com/demo/dragDropMooTools htm
Code:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.maximize_window()
driver.get('http://sahitest.com/demo/dragDropMooTools.htm')
dragger = driver.find_element_by_id('dragger') # Dragged element
item1 = driver.find_element_by_xpath('//div[text()="Item 1"]') # The target element 1
item2 = driver.find_element_by_xpath('//div[text()="Item 2"]') # The target 2
item3 = driver.find_element_by_xpath('//div[text()="Item 3"]') # The target 3
item4 = driver.find_element_by_xpath('//div[text()="Item 4"]') # The target 4
action = ActionChains(driver)
action.drag_and_drop(dragger, item1).perform() # 1. mobile dragger To the target 1
sleep(2)
action.click_and_hold(dragger).release(item2).perform() # 2. The effect is the same as the above sentence, also can have the mobile effect
sleep(2)
action.click_and_hold(dragger).move_to_element(item3).release().perform() # 3. The effect is the same as the above two sentences, but also can move the effect
sleep(2)
# action.drag_and_drop_by_offset(dragger, 400, 150).perform() # 4. Move to specified coordinates
action.click_and_hold(dragger).move_by_offset(400, 150).release().perform() # 5. And on the 1 Same sentence, move to the specified coordinates
sleep(2)
driver.quit()
Results:
dropped dropped dropped dropped
Method 1 in the previous example is enough. If you look at the source code, you will find that method 2 is actually the implementation of drag_and_drop() in method 1. Note: pay attention to the wait time when using drag and drop, sometimes it will fail due to the speed is too fast.
4. Key
There are several ways to simulate keystrokes, including win32api, SendKeys, and send_keys() of selenium's WebElement object. The ActionChains class also provides several methods to simulate keystrokes.
http sample url: / / sahitest com/demo/keypress htm
Code 1:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.maximize_window()
driver.get('http://sahitest.com/demo/keypress.htm')
key_up_radio = driver.find_element_by_id('r1') # Monitor key rising
key_down_radio = driver.find_element_by_id('r2') # The monitor button is pressed
key_press_radio = driver.find_element_by_id('r3') # The monitor button is pressed to rise
enter = driver.find_elements_by_xpath('//form[@name="f1"]/input')[1] # Input box
result = driver.find_elements_by_xpath('//form[@name="f1"]/input')[0] # Monitoring results
# monitoring key_down
key_down_radio.click()
ActionChains(driver).key_down(Keys.CONTROL, enter).key_up(Keys.CONTROL).perform()
print result.get_attribute('value')
# monitoring key_up
key_up_radio.click()
enter.click()
ActionChains(driver).key_down(Keys.SHIFT).key_up(Keys.SHIFT).perform()
print result.get_attribute('value')
# monitoring key_press
key_press_radio.click()
enter.click()
ActionChains(driver).send_keys('a').perform()
print result.get_attribute('value')
driver.quit()
Results:
key downed charCode=[0] keyCode=[17] CTRL
key upped charCode=[0] keyCode=[16] NONE
key pressed charCode=[97] keyCode=[0] NONE
Example 2:
http sample url: / / sahitest com/demo/label htm
Code:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from time import sleep
driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.maximize_window()
driver.get('http://sahitest.com/demo/label.htm')
input1 = driver.find_elements_by_tag_name('input')[3]
input2 = driver.find_elements_by_tag_name('input')[4]
action = ActionChains(driver)
input1.click()
action.send_keys('Test Keys').perform()
action.key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).perform() # ctrl+a
action.key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform() # ctrl+c
action.key_down(Keys.CONTROL, input2).send_keys('v').key_up(Keys.CONTROL).perform() # ctrl+v
print input1.get_attribute('value')
print input2.get_attribute('value')
driver.quit()
Results:
Test Keys
Test Keys
Copy and paste using WebElement < input > send_keys() can also be implemented, you can try 1, you can also use the lower level method, which is also win32api, SendKeys, keybd_event if you are interested