Play Python Selenium mouse keyboard operation (actionchains) _python

Source: Internet
Author: User

Use selenium to do automation, sometimes encounter needs to simulate mouse operation can be done, such as click, double-click, click the right mouse button, drag and so on. And selenium gives us a class to handle this kind of event--actionchains

Selenium.webdriver.common.action_chains.ActionChains (Driver)

This class is basically able to meet all of our needs for mouse operation.

1.ActionChains Basic Usage

The first thing you need to know about Actionchains is that when you call the Actionchains method, you don't execute it immediately, you put all the actions in one queue, and when you call the Perform () method, the time in the queue executes sequentially.

In this case we can have two methods of calling:

• Chain Style

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 notation

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 types of writing are essentially the same, and Actionchains will perform all the operations in sequence.

2.ActionChains Method List

Click (on_element=none)--clicking the left mouse button

Click_and_hold (On_element=none)--click the left mouse button, do not release

Context_click (On_element=none)--Click the right mouse button

Double_click (On_element=none)--double-click the left mouse button

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

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)--Loosen a key

Move_by_offset (Xoffset, Yoffset)--moving the mouse from the current position to a coordinate

Move_to_element (to_element)--mouse moves to an element

Move_to_element_with_offset (To_element, Xoffset, Yoffset)--Move to the location of the distance from an element (upper-left coordinate)

Perform ()--all actions in the chain of execution

Release (On_element=none)--Releasing 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)--sends a key to the specified element

Next, use the example to specify and demonstrate the use of each method:

3. code example

1. Click action

Sample URL http://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 ()
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 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 () # Chained usage

print driver.find_element_by_name (' T2 '). get_ Attribute (' value ') Sleep

(2)
driver.quit ()

Results:

[Click] [Double_click] [Right_click]

2. Mouse movement

Sample URL http://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 () Driver.maximize_window () driver.get (' http://sahitest.com/demo/mouseover.htm ') Write = Driver.find_element_by_xpath ('//input[@value = ' write on hover] ') # mouse moves to this element, and "Mouse moved" appears in the following input box blank = Driver.find_element_by_xpath ('//input[@value = "Blank on Hover"]) # The mouse moves to this element, emptying the contents of the input box below result = Driver.find_ Element_by_name (' t1 ') action = Actionchains (Driver) action.move_to_element (write). Perform () # moved to write, displaying ' Mouse moved "Print Result.get_attribute (' value ') # action.move_to_element (blank). Perform () Action.move_by_offset (10, 50). Perform () # moves to the point at the current position (10,50), the same as the previous sentence, moves to the blank, empties the print Result.get_attribute (' value ') action.move_to_element_with
_offset (blank, -40). Perform () # moves to the point from the blank element (10,-40) and moves to the print result.get_attribute (' value ') sleep (2) on write

 Driver.quit ()

Results

Mouse moved

Mouse moved

3. Dragging and dragging

Sample URL http://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 () 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"] # target element 1 item2 = Driver.find_element_by_xpath ('//div[text () = ' Item 2] ') # target 2 Item3 = Driver.find_el Ement_by_xpath ('//div[text () = ' Item 3] ') # target 3 item4 = Driver.find_element_by_xpath ('//div[text () = ' Item 4] ') # Target 4 acti On = 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 the previous sentence, and can also play a moving effect sleep (2) action.click_and_hold (Dragger). move_to_ Element (ITEM3). Release (). Perform () # 3. The effect is the same as the previous two sentences, and can also play a moving 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 (). Release (). Perform () # 5. As in the previous sentence, move to the specified coordinate sleep (2) driver.quit ()

 

Results:

Dropped dropped dropped dropped

The general use of coordinate positioning is very little, using the example in the method 1 enough, if you look at the source code, you will find that method 2 is actually method 1 in the implementation of the Drag_and_drop (). Note: Drag-and-drop use to pay attention to the wait time, sometimes because the speed is too fast to fail.

4. Press

There are many methods to simulate the key, can use Win32API to realize, can use SendKeys to realize, also can use Selenium Webelement object's Send_keys () method to realize, here Actionchains class also provides several simulation key method.

Sample URL http://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 () Driver.maximize_window () driver.get (' http://sahitest.com/demo/keypress.htm ') Key_up_radio = driver.find_element_by_id (' r1 ') # Monitor key to Rise Key_down_radio = driver.find_element_by_id (' R2 ') # Monitor Button Press Key_ Press_radio = driver.find_element_by_id (' r3 ') # Monitor key Press to raise Enter = Driver.find_elements_by_xpath ('//form[@name = ' F1 ']/ Input ') [1] # Enter box result = Driver.find_elements_by_xpath ('//form[@name = ' F1 ']/input ') [0] # Monitoring results # monitoring Key_down Key_down_radi O.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:

Sample URL http://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 ()
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 paste with webelement< input >.send_keys () can also be achieved, we can try, you can also use a more low-level method, but also the OS bullet box one of the Win32API, interested can also try SendKeys, Keybd_event

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.