Operate the pythonselenium mouse and keyboard (ActionChains)

Source: Internet
Author: User
This article mainly introduces pythonselenium mouse and keyboard operations (ActionChains) in detail and teaches you how to play with selenium mouse and keyboard. if you are interested, refer to selenium for automation, sometimes you may need to simulate a mouse operation, such as clicking, double-clicking, right-clicking, and dragging. Selenium provides us with 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

First, you need to understand the Execution Principle of ActionChains. when you call the ActionChains method, it will not be executed immediately, but will store all the operations in a queue in order. when you call perform () method, the time in the queue is executed in sequence.

In this case, we can have two call methods:

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

The two statements are essentially the same, and ActionChains perform all the operations in sequence.

2. ActionChains method list

Click (on_element = None) -- 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

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

Drag_and_drop (source, target) -- drag to an element and release it.

Drag_and_drop_by_offset (source, xoffset, yoffset) -- drag to a coordinate and release

Key_down (value, element = None) -- press the key on a keyboard

Key_up (value, element = None) -- release a key

Move_by_offset (xoffset, yoffset) -- move the cursor from the current position to a coordinate

Move_to_element (to_element) -- move the cursor to an element

Move_to_element_with_offset (to_element, xoffset, yoffset) -- the distance from an element (coordinate in the upper left corner)

Perform () -- execute all actions in the chain

Release (on_element = None) -- release the left mouse button at an element position

Send_keys (* keys_to_send) -- The element that sends a key to the current focus.

Send_keys_to_element (element, * keys_to_send) -- send a key to a specified element

The following example is used to describe in detail and demonstrate the usage of each method:

3. Sample code

1. click to operate

Sample url #;

Code:

#-*-Coding: UTF-8-*-from selenium import webdriverfrom selenium. webdriver. common. action_chains import ActionChainsfrom time import sleepdriver = 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 doubleclick_btn = driver. find_element_by_xpath ('// input [@ value = "dbl click me"]') # Double-click the rightclick_btn = driver. find_element_by_xpath ('// input [@ value = "right click me"]') # right-click the ActionChains (driver) button ). click (click_btn ). double_click (doubleclick_btn ). context_click (rightclick_btn ). perform () # chained usage print driver. find_element_by_name ('T2 '). get_attribute ('value') sleep (2) driver. quit ()

Result:

[CLICK] [DOUBLE_CLICK] [RIGHT_CLICK]

2. move the mouse

Sample url #;

Sample code:

#-*-Coding: UTF-8-*-from selenium import webdriverfrom selenium. webdriver. common. action_chains import ActionChainsfrom time import sleepdriver = 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"]') # Move the cursor to this element and "Mouse moved" blank = driver will be displayed in the input box below. find_element_by_xpath ('// input [@ value = "Blank on hover"]') # Move the cursor to this element and clear the result = driver in the following input box. find_element_by_name ('T1') action = ActionChains (driver) action. move_to_element (write ). perform () # Move to write to display "Mouse moved" print result. get_attribute ('value') # action. move_to_element (blank ). perform () action. move_by_offset (10, 50 ). perform () # Move to the point (10, 50) from the current position, which has the same effect as the previous sentence. Move to blank and clear the print result. get_attribute ('value') action. move_to_element_with_offset (blank, 10,-40 ). perform () # Move to the point (10,-40) from the blank element, you can move to print result on write. get_attribute ('value') sleep (2) driver. quit ()

Result

Mouse moved

Mouse moved

3. drag

Sample url #;

Code:

#-*-Coding: UTF-8-*-from selenium import webdriverfrom selenium. webdriver. common. action_chains import ActionChainsfrom time import sleepdriver = webdriver. firefox () driver. implicitly_wait (10) driver. maximize_window () driver. get (' http://sahitest.com/demo/dragDropMooTools.htm ') Dragger = driver. find_element_by_id ('dragger ') # item1 = driver. find_element_by_xpath ('// p [text () = "Item 1"]') # target element 1item2 = driver. find_element_by_xpath ('// p [text () = "Item 2"]') # target 2item3 = driver. find_element_by_xpath ('// p [text () = "Item 3"]') # target 3item4 = driver. find_element_by_xpath ('// p [text () = "Item 4"]') # destination 4 action = ActionChains (driver) action. drag_and_drop (dragger, item1 ). perform () #1. move dragger to target 1 sleep (2) action. click_and_hold (dragger ). release (item2 ). perform () #2. the effect is the same as that in the previous sentence, and the moving effect can also be sleep (2) action. click_and_hold (dragger ). move_to_element (item3 ). release (). perform () #3. the effect is the same as that of the previous two sentences, and the result can also be moved. sleep (2) # action. drag_and_drop_by_offset (dragger, 400,150 ). perform () #4. move to the specified coordinate action. click_and_hold (dragger ). move_by_offset (400,150 ). release (). perform () #5. same as the previous sentence, move to the specified coordinate sleep (2) driver. quit ()

Result:

Dropped

Usually there are few positioning by Coordinates. it is enough to use method 1 in the above example. 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: When using drag and drop, pay attention to the waiting time. sometimes it will fail because the speed is too fast.

4. buttons

There are multiple methods to simulate keys, which can be implemented using win32api, SendKeys, or send_keys () of the WebElement object of selenium, here, the ActionChains class also provides several methods to simulate buttons.

Sample url #;

Code 1:

#-*-Coding: UTF-8-*-from selenium import webdriverfrom selenium. webdriver. common. action_chains import ActionChainsfrom time import sleepdriver = 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') # The monitoring key is raised by key_down_radio = driver. find_element_by_id ('R2 ') # Press the monitoring key to press key_press_radio = driver. find_element_by_id ('r3 ') # Press the monitoring button and 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 result # monitoring key_downkey_down_radio.click () ActionChains (driver ). key_down (Keys. CONTROL, enter ). key_up (Keys. CONTROL ). perform () print result. get_attribute ('value') # monitor key_upkey_up_radio.click () enter. click () ActionChains (driver ). key_down (Keys. SHIFT ). key_up (Keys. SHIFT ). perform () print result. get_attribute ('value') # monitor key_presskey_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

Example 2:

Sample url #;

Code:

# -*- coding: utf-8 -*-from selenium import webdriverfrom selenium.webdriver.common.action_chains import ActionChainsfrom selenium.webdriver.common.keys import Keysfrom time import sleepdriver = 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+aaction.key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform() # ctrl+caction.key_down(Keys.CONTROL, input2).send_keys('v').key_up(Keys.CONTROL).perform() # ctrl+vprint input1.get_attribute('value')print input2.get_attribute('value')driver.quit()

Result:

Test Keys
Test Keys

Copy and paste WebElement <input>. send_keys () can also be implemented. you can try it or use a more underlying method. it is also one of the win32api solutions for the OS pop-up box. if you are interested, try SendKeys and keybd_event.

The above is all the content of this article. I hope it will help you learn and support PHP.

For more articles about how to play python selenium mouse and keyboard operations (ActionChains), please follow PHP's Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.