English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Mastering Mouse and Keyboard Operations in Python Selenium (ActionChains)

When using selenium for automation, there are sometimes situations where you need to simulate mouse operations to proceed, such as single-click, double-click, right-click, drag and drop, etc. Selenium provides a class to handle such events - ActionChains

selenium.webdriver.common.action_chains.ActionChains(driver)

This class can basically meet all our needs for mouse operations.

1.ActionChains basic usage

Firstly, we need to understand the execution principle of ActionChains. When you call a method of ActionChains, it will not execute immediately, but will store all operations in order in a queue. When you call the perform() method, the operations in the queue will be executed sequentially.

In this case, we can have two ways of calling: 

•Chaining 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()

 •Step-by-step writing

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()

 Both writing methods are essentially the same, ActionChains will execute all operations in order.

2. List of ActionChains methods

click(on_element=None) ——Single-click the left mouse button

click_and_hold(on_element=None) ——Click the left mouse button and do not release

context_click(on_element=None) ——Right-click the mouse

double_click(on_element=None) ——Double-click the left mouse button

drag_and_drop(source, target) ——Drag to a certain element and then release

drag_and_drop_by_offset(source, xoffset, yoffset) ——Drag to a certain coordinate and then release

key_down(value, element=None) ——Press a key on the keyboard

key_up(value, element=None) ——Release a certain key

move_by_offset(xoffset, yoffset) ——Move the mouse from the current position to a certain coordinate

move_to_element(to_element) ——Move the mouse to a certain element

move_to_element_with_offset(to_element, xoffset, yoffset) ——Move to a position how many distances from a certain element (upper left corner coordinates)

perform() ——Execute all actions in the chain

release(on_element=None) ——Release the left mouse button at a certain element position

send_keys(*keys_to_send) ——Send a key to the currently focused element

send_keys_to_element(element, *keys_to_send) ——Send a key to the specified element

Next, let's use examples to illustrate and demonstrate the usage of each method in detail:

3. Code example

1. Click operation

示例网址http://sahitest.com/demo/clicks.htm

代码:

# -*- 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 button
doubleclick_btn = driver.find_element_by_xpath('//input[@value="dbl click me"]') # Double-click 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() # Chaining usage
print driver.find_element_by_name('t2').get_attribute('value')
sleep(2)
driver.quit()

Result:

[CLICK][DOUBLE_CLICK][RIGHT_CLICK]

2.mouse move

示例网址http://sahitest.com/demo/mouseover.htm

Example 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"]') # When the mouse moves to this element, 'Mouse moved' will be displayed in the below input box
blank = driver.find_element_by_xpath('//input[@value="Blank on hover"]') # When the mouse moves to this element, it will clear the content in the below input box
result = driver.find_element_by_name('t1')
action = ActionChains(driver)
action.move_to_element(write).perform() # Move to 'write' and display 'Mouse moved'
print result.get_attribute('value')
# action.move_to_element(blank).perform()
action.move_by_offset(10, 50).perform() # Move to the distance from the current position (10,50) with the same effect as the previous sentence, move to 'blank' and clear
print result.get_attribute('value')
action.move_to_element_with_offset(blank, 10, -40).perform() # Move to the distance from the 'blank' element (10,-4The point (0) can be moved to 'write'
print result.get_attribute('value')
sleep(2)
driver.quit()

Result

Mouse moved

Mouse moved

3.drag

示例网址http://sahitest.com/demo/dragDropMooTools.htm

代码:

# -*- 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') # The element to be dragged
item1 ') # Target//] = driver.find_element_by_xpath(' 1] = driver.find_element_by_xpath('1
item2 ') # Target//] = driver.find_element_by_xpath(' 2') # Target element2
item3 ') # Target//] = driver.find_element_by_xpath(' 3') # Target element3
item4 ') # Target//] = driver.find_element_by_xpath(' 4') # Target element4
action = ActionChains(driver)
] = driver.find_element_by_xpath('1).drag_and_drop(dragger, item 1div[text()="Item1
sleep(2)
).target2).drag_and_drop(dragger, item 2).perform() #
sleep(2)
).move_to_target3).release(item 3).perform() #
sleep(2)
).move_to_element(item 4.move_by_offset( 15).release().perform() # 4# action.drag_and_drop_by_offset(dragger,
).move_to_element((0)).perform() #4.move_by_offset( 1500, 5).move_to_element((0)).release().perform() #
sleep(2)
driver.quit()

Result:

dropped dropped dropped dropped

is generally used to locate by coordinates rarely, and use the method in the example1is enough, if you look at the source code, you will find that the method2That is, the method1to implement drag_and_drop(). Note: When dragging, pay attention to the waiting time, as it may fail due to too fast speed.

4.key

There are many ways to simulate key presses, and it can use win32can be implemented using SendKeys, or using the send_keys() method of the selenium WebElement object, and the ActionChains class also provides several methods to simulate key presses.

示例网址http://sahitest.com/demo/keypress.htm

Code1:

# -*- 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/') # Key press event
key_up_radio = driver.find_element_by_id('r1') # Monitor key rise
key_down_radio = driver.find_element_by_id('r2') # Monitor key press
key_press_radio = driver.find_element_by_id('r3') # Monitor key press to rise
enter = driver.find_elements_by_xpath('//form[@name="f1"]/input')]1] # 输入框
result = driver.find_elements_by_xpath('//form[@name="f1"]/input')[0] # 监测结果
# 监测key_down
key_down_radio.click()
ActionChains(driver).key_down(Keys.CONTROL, enter).key_up(Keys.CONTROL).perform()
print result.get_attribute('value')
# 监测key_up
key_up_radio.click()
enter.click()
ActionChains(driver).key_down(Keys.SHIFT).key_up(Keys.SHIFT).perform()
print result.get_attribute('value')
# 监测key_press
key_press_radio.click()
enter.click()
ActionChains(driver).send_keys('a').perform()
print result.get_attribute('value')
driver.quit()

Result:

key downed charCode=[0] keyCode=[17] CTRL
key upped charCode=[0] keyCode=[16] NONE
key pressed charCode=[97] keyCode=[0] NONE

示例2:

示例网址http://sahitest.com/demo/label.htm

代码:

# -*- 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()

Result:

Test Keys
Test Keys

Copy and paste can also be realized using WebElement<input>.send_keys(), you can try it, and you can also use a more underlying method, which is also one of the ways to handle os pop-up windows, win32api, you can also try SendKeys, keybd_event if you are interested

That's all for this article. Hope it helps everyone's learning and also hope everyone will support the Naiya Tutorial more.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been edited by humans, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (When reporting via email, please replace # with @) for reporting violations, and provide relevant evidence. Once verified, this site will immediately delete the suspected infringing content.