How To Automate Mouse Clicks With Selenium Python

Paulo Oliveira

Posted On: November 9, 2022

view count289817 Views

Read time22 Min Read

Sometimes, in our test code, we need to handle actions that apparently could not be done automatically. For example, some mouse actions such as context click, double click, drag and drop, mouse movements, and some special key down and key up actions. These specific actions could be crucial depending on the project context.

Together Python & Selenium are the third most popular technology according to Stack Overflow Developer Survey 2021 and the most used frontend test automation framework. Test automation has become essential in all software development projects because agile business needs increasingly require faster development and delivery.

In this Selenium Python tutorial on how to automate mouse clicks with Selenium Python, we will learn how to automate essential mouse click actions with Python and Selenium using the ActionChains library. We will learn from the prerequisites needed to install and configure your environment to run the tests directly on cloud Selenium Grid like LambdaTest.

So, let’s get started!

Why Python & Selenium for Test Automation?

Python was created to be simple, open-source, with excellent readability, and a cross-platform language (it can run on any operating system and device).

When writing this blog on how to automate mouse clicks with Selenium Python, 3.11 is the latest version of Python. It is a programming language that is constantly being updated and has excellent community support.

According to Stack Overflow Trends, Python has gained prominence over the years and has become the most popular language, as seen in the chart below.

Stack Overflow Trends

Python is one of the most used programming languages for test automation, and there are many reasons for it. If you want to learn more about it, you can check out this blog on Python automation testing.

Python automation testing with Selenium is a killer combination for web automation testing. Selenium is open-source and one of the most popular test automation frameworks that support six popular programming languages, including Python. When writing this blog on how to automate mouse clicks with Selenium Python, the latest version of Selenium is Selenium 4.

What is ActionChains?

ActionChains is a Python library that lets you automate low-level interactions such as context click, double click, drag and drop, mouse movements, and some special key down and key up actions. ActionChains is very useful for executing complex actions using the keyboard and mouse.

To use the ActionChains library, you need to create an ActionChains object that can call methods to perform some actions sequentially, one by one. The called actions are pushed into a queue, and when calling the “perform” method, they are fired and performed in the same order in which they were queued.

Syntax:

First, we would like to show you how to create an object using the ActionChains library.

To use the ActionChains method, you just need to import the library and instantiate the object in a variable, calling the library constructor passing the browser element that is the instance of the browser that the actions will be executed.

ActionChains supports a lot of mouse actions. Below are all the methods (mouse and keyboard) supported by the ActionChains library:

click

Description: Performs a click operation on an element.
Syntax: click(element)

  • element: WebElement to be clicked with the left mouse button.
  • click_and_hold

    Description: Performs the action of holding the left mouse button to an element.
    Syntax: click_and_hold(element)

  • element: WebElement to be clicked and held with left mouse button
  • context_click

    Description: Performs a right-click operation on an element.
    Syntax: context_click(element)

  • element: WebElement to be clicked with the right mouse button.
  • double_click

    Description: Performs a double-click operation on an element.
    Syntax: double_click(element)

  • element: WebElement to be clicked twice with the left mouse button.
  • drag_and_drop

    Description: Performs the action of holding the left mouse button on the source element. Then moves to the target element and finally releases the mouse button.
    Syntax: drag_and_drop(element, target)

  • element: WebElement to mouse down.
  • target: WebElement to mouse up.
  • drag_and_drop_by_offset

    Description: Performs the action of holding the left mouse button on the source element. Then moves to the target offset and finally releases the mouse button.

    Syntax: drag_and_drop_by_offset (element, xoffset, yoffset)

  • element: WebElement to mouse down.
  • xoffset: X offset to move the element to.
  • yoffset: Y offset to move the element to.
  • key_down

    Description: Performs a key press only action without releasing it. It should only be used by modifier keys like CTRL and ALT.
    Syntax: key_down(key)

  • key: Key to be pressed.
  • key_up

    Description: Releases a key that was previously pressed.
    Syntax: key_up(key)

  • key: Key to be released.
  • move_by_offset

    Description: Performs movement of the mouse to an offset from the present position of the mouse.
    Syntax: move_by_offset(xoffset, yoffset)

  • xoffset: X offset to move to.
  • yoffset: Y offset to move to.
  • move_to_element

    Description: Performs mouse movement to the middle of the element.
    Syntax: move_to_element(element)

  • element: WebElement where the mouse should be moved to.
  • move_to_element_with_offset

    Description: Performs movement of the mouse by the offset of the element specified on the page. The offsets are for the top left corner of the element.

    Syntax: move_to_element_with_offset(element, xoffset, yoffset)

  • element: WebElement to move to.
  • xoffset: X offset to move to.
  • yoffset: Y offset to move to.
  • perform

    Description: Performs all the actions queued one after the other.
    Syntax: perform()

    pause

    Description: Performs stopping all inputs for a particular duration of time.
    Syntax: pause(seconds)

  • seconds: Duration (in seconds) to pause a particular input action.
  • release

    Description: Performs releasing a held mouse button on an element.
    Syntax: release(element)

  • element: WebElement to be released.
  • reset_actions

    Description: Performs the action of resetting all the actions stored locally and on to the remote end.

    Syntax: reset_actions()

    send_keys

    Description: Performs the action of sending keys to the present element, which is focused. It can also be used for modifier keys, like CTRL, ALT, and more. You can also use a combination of different keys by leveraging ActionChains in Selenium Python.

    Syntax: send_keys(keys)

  • keys: Keys to be sent.
  • We will see some of the frequently used actions in the further sections of this blog on how to automate mouse clicks with Selenium Python.

    Demonstration: How to automate mouse clicks with Selenium Python?

    The primary purpose of this blog is to show you how to automate mouse clicks with Selenium Python in Chrome web pages on a Windows device.

    We are going to do this by executing the following test scenarios, that will demonstrate the usage of the following ActionChains methods:

    • double_click
    • click
    • context_click
    • move_to_element
    • move_to_element_with_offset
    • move_by_offset
    • drag_and_drop
    • drag_and_drop_by_offset

    The demonstration will be done on a cloud Selenium Grid like LambdaTest, a continuous quality testing cloud platform that helps developers and testers ship code faster. Cloud-based cross browser testing platforms like LambdaTest provides an online browser farm of 3000+ browsers and operating systems to perform Selenium Python testing at scale.

    You can also Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorials around automated browser testing, Selenium testing, Cypress E2E testing, CI/CD, and more.

    To run the test on the LambdaTest cloud grid is to use the capabilities to configure the environment where the test will run.

    In this blog on how to automate mouse clicks with Selenium Python, we are going to run the tests with the following characteristics:

    • Selenium 4
    • OS: Windows 11
    • Browser: Chrome
    • Browser Version: “latest”
    • Resolution: 1024 x 768

    You can generate the capabilities code from the LambdaTest Capabilities Generator.

    automation capability generator

    The generated code for our environment is presented below.

    You have to put this code just after the imports and fill in the variables with the proper information.

    Then you should configure these three variables.

    1. You can get the “Username” and “Access Token” from your LambdaTest Profile Section.
    2. Finally, you have to set the URL where the test will run, with a default format, and the code that will instantiate the driver in a variable called “browser”.

    Prerequisites: Setup Process

    To start our coding, we need to proceed with the following steps to set up Python, Selenium, and Visual Studio Code.

    Step 1: Download and Install Python

    First, you must download and install Python according to your operating system.

    Step 2: Install Selenium WebDriver

    Selenium WebDriver can be installed simply using the pip install manager. PIP is a package management system used to install/manage packages and libraries written in Python.

    Quick Note: ActionChains is installed within the Selenium WebDriver library, so you just need to use it.

    Step 3: Download and Install Visual Studio Code

    Visual Studio Code (VSC) is one of the most used coding IDEs. For our coding demonstration, we are going to use Visual Studio Code.

    You are free to use your preferable IDE; everything that we will show in this blog on how to automate mouse clicks with Selenium Python will work in any IDE. Choose yours!

    Opening a webpage on Chrome

    According to our test scenarios, we first need to open a specific webpage. We will show how you can do this for the first scenario webpage, the Table Sort And Search LambdaTest Playground page, and you can use the same code for the other scenarios, just changing the URL.

    First, you must import the Selenium WebDriver that is needed for Selenium WebDriver to interact with the browser.

    Then, you have to insert LambdaTest capabilities as shown in the previous session, inform the URL in the correct structure for running in the LambdaTest grid, and then instantiate the driver in a variable called “browser”.

    Finally, you need to use the browser instance to access the desired webpage, using the function “get” and informing the URL of the website that should be opened.

    Extra Tip 1: If you want a better view, you can maximize your browser window using the below code right after the driver instantiation.

    Extra Tip 2: You should use the below code to close the browser window when finishing your test. This code must be the last line of your script.

    For more tips, refer to our blog on 16 Selenium Best Practices for Efficient Test Automation to efficiently use Selenium WebDriver.

    How to perform Double Click on an element in Selenium with Python?

    We would use the double_click(element) method of ActionChains to double-click on a WebElement in the DOM. Shown below is the test scenario:

    Test Scenario:

      1. Open Table Sort And Search LambdaTest Playground page.
      2. Double-click on the Age column title.
      3. Check that the list was ordered by Age (descendent) so that the first two rows have 66 in the Age column.

    You can view the page where we will automate some actions in the picture below.

    table sort and search

    Implementation:

    Code Walkthrough:

    The first part of the script will be the necessary code to open the desired page, as shown in the previous section of this blog on how to automate mouse clicks with Selenium Python.

    Selenium Python

    Then, we need to locate the element we will double-click. In this scenario, will be the Age column title.

    First, you must import the By method from selenium.webdriver.common.by.

    selenium webdriver

    Then, you should locate the element using XPath. You can see the page elements information, and you will find the Age column title element.

    locate the element using XPath

    As you can see, the element is shown in the details below. We can locate this element using the “th” element, which has the “aria-label” attribute with the “Age: activate to sort column ascending” value. We are going to store the element in a variable called age_sorting.

    The code for locating the element is shown below.

    xpath element

    For more information about how to automate mouse clicks using Selenium Python, you can look at this blog on how to automate web forms with Python. You can check our XPath Locators Cheat Sheet to learn more about using XPath.

    After locating the element, we will create the most important part of the code, which is to use ActionChains to double-click the element.

    First we need to instantiate an ActionChains element, which we will call “actions”, as was shown in the previous session.

    ActionChains element

    Then, we should use the ActionChains method “double_click”, informing the element we want to double-click that it is stored in the age_sorting variable.

    double-click

    Finally, we need to execute the ActionChains method “perform.

    To check if after the double click, the first two lines of the table have 66 as the age, we should locate the age in the first two lines using XPath again.

    XPath

    Then, we can finally assert that first_age and second_age have “66” in their values.

    assert that first age

    How to perform Click in Selenium with Python?

    We would use the click(element) method of ActionChains to click on a WebElement in the DOM. Shown below is the test scenario:

    Test Scenario:

    1. Open Simple Form Demo LambdaTest Playground page.
    2. Click in the message field.
    3. Write “Hello!” in the message field.
    4. Click on the button “Get Checked Value”.
    5. Check that the message is presented as “Hello!”.

    You can view the page where we will automate some actions in the picture below.

    simple form demo

    Implementation:

    Code Walkthrough:

    In this test scenario, we will need to locate the message field, the button, and the “your message” area of the first form. These fields can be located by id, making our code more simple.

    your message area

    Then, we should again instantiate an element called “actions”.

    element actions

    The first action will be to click on the message field. We have to use the method “click,” and in the method parameter “on_element” we should point to the “message_field” variable.

    click on the message field

    The second action will be to type “Hello!” In the field, we can do this using the “send_key” method.

    send_key

    The third step will be to click on the button.

    click on the button

    Finally, we should call the “perform” method.

    perform method

    Just to finish, you can check if your presented message on the right side of the form is “Hello!”.

    presented message

    How to perform Context Click in Selenium with Python?

    We would use the context_click(element) method of ActionChains to click on a WebElement in the DOM with the right mouse button. Shown below is the test scenario:

    Test Scenario:

    1. Open Simple Form Demo LambdaTest Playground page.
    2. Click in the message field.
    3. Perform a right mouse click (context click).

    You can view the page where we will automate some actions in the picture below.

    Simple Form Demo

    Implementation:

    Code Walkthrough:

    In this test scenario, we will need to locate the message field, the button, and the “your message” area of the first form. These fields can be located by id, making our code more simple.

    message field

    Then, we should again instantiate an element called “actions”.

    Action Chains

    The first action will be to click on the message field. We have to use the method “click,” and in the method parameter “on_element” we should point to the “message_field” variable.

    on_element

    The second action will be to click with the right mouse button and type “Hello!” In the field, we can do this using the “context_click” method.

    context_click

    Finally, we should call the “perform” method.

    action perform

    How to perform Move to Element in Selenium with Python?

    We would use the move_to_element(element) method of ActionChains to move the mouse to a WebElement in the DOM. Shown below is the test scenario:

    Test Scenario:

    1. Open Mouse Hover LambdaTest Playground page.
    2. Move the mouse cursor to the first picture.
    3. Check that the text “Hover” is shown below the image.

    You can view the page where we will automate some actions in the picture below.

    Mouse Hover

    Implementation:

    Code Walkthrough:

    In this test scenario, we will need to locate the first image on the page. We can do this using XPath again and storing the element in the “first_image” variable.

    first_image XPath

    Then, we should again instantiate an element called “actions”.

    Actions chain browser

    To move the mouse cursor to the first image, we should call the “move_to_element” method, passing the “first_image” variable as a parameter. Finally, we can call the “perform” method to execute it.

    move_to_element

    We will locate an element called “message”, that is shown below the image with “Hover” text, when the mouse is on the image. We can again use XPath to locate it and then assert that the presented message is correct.

    image with “Hover”

    How to perform Move to Element by Offset in Selenium with Python?

    We would use the move_to_elemenet_with_offset(element, xoffset, yoffset) method of ActionChains to perform mouse movement by offsetting the specified WebElement in the DOM. Shown below is the test scenario:

    Test Scenario:

    1. Open Mouse Hover LambdaTest Playground page.
    2. Move the mouse cursor to the first picture using offset values.
    3. Check that the text “Hover” is shown below the image.

    You can have a quick view of the page where we will automate some actions in the picture below.

    Mouse Hover

    Implementation:

    Code Walkthrough:

    In this test scenario, we will need to locate the first image on the page. We can do this using XPath again and storing the element in the “first_image” variable.

    first_image” variable

    Then, we should again instantiate an element called “actions”.

    Actions chain browser

    To move the mouse cursor to the first image, we should call the “move_to_element_with_offset” method, passing the “first_image” variable as a parameter and the two offset values. In our example, we use 100 to xoffset and 200 to yoffset.

    Finally, we can call the “perform” method to execute it.

    move_to_element_with_offset

    We will again locate an element “message”, that is shown below the image with “Hover” text, when the mouse is on the image. We can again use XPath to locate it and then assert that the presented message is correct.

    image with “Hover”

    How to perform Move by Offset in Selenium with Python?

    We would use the move_by_offset(xoffset, yoffset) method of ActionChains to perform mouse movement by offsetting the current mouse position. Shown below is the test scenario:

    Test Scenario:

    1. Open Mouse Hover LambdaTest Playground page.
    2. Move the mouse cursor to a specific position using offset values.
    3. Check that the text “Hover” is shown below the image.

    You can view the page where we will automate some actions in the picture below.

    Mouse Hover

    Implementation:

    Code Walkthrough:

    In this test scenario, we will start instantiating an element called “actions”.

    Actions chain browser

    To move the mouse cursor to a specific offset position, we should call the “move_by_offset” method, passing the two offset values. In our example, we are using 617 to xoffset and 593 to yoffset.

    Finally, we can call the “perform” method to execute it.

    move_by_offset method

    How to perform Drag and Drop in Selenium with Python?

    We would use the drag_and_drop(element, target) method of ActionChains to drag a WebElement in the DOM to a specific target element. Shown below is the test scenario:

    Test Scenario:

    1. Open the Drag and Drop Demo LambdaTest Playground page.
    2. In the second drag-and-drop demo, drag and drop the draggable element to the “Drop Here” area.
    3. Check that the “Drop Here” message changes to “Dropped!”.

    You can view the page where we will automate some actions in the picture below.

    Drag and Drop Demo

    Implementation:

    Code Walkthrough:

    In this test scenario, we will need to locate the draggable WebElement and the drop area, another WebElement. We can use XPath again and store the element in “draggable” and “droparea” variables.

    draggable and droparea

    Then, we should again instantiate an element called “actions”.

    Actions chain browser

    To drag and drop the element, we should call the “drag_and_drop” method, passing the “draggable” and “droparea” variables as parameters.

    Finally, we can call the “perform” method to execute it.

    drag_and_drop

    We will again locate an element “message” shown inside the droparea with “Dropped!” text when the WebElement is dropped. We can again use XPath to locate it and then assert that the presented message is correct.

    WebElement is dropped

    How to perform Drag and Drop by Offset in Selenium with Python?

    We would use the drag_and_drop_by_offset(element, xoffset, yoffset) method of ActionChains to drag a WebElement in the DOM to a specific target offset. Shown below is the test scenario:

    Test Scenario:

    1. Open the Drag and Drop Demo LambdaTest Playground page.
    2. In the second drag-and-drop demo, drag and drop the draggable element to the “Drop Here” area using offset values.
    3. Check that the “Drop Here” message changes to “Dropped!”

    You can view the page where we will automate some actions in the picture below.

    Drop Here” message changes to “Dropped

    Implementation:

    Code Walkthrough:

    In this test scenario, we will again need to locate the draggable WebElement. We can do this using XPath again and storing the element in the “draggable” variable.

    XPath again and storing the element in the “draggable

    Then, we should again instantiate an element called “actions”.

    element called “actions”.

    To drag and drop the element by offset, we should call the “drag_and_drop_by_offset” method, passing the “draggable” variables and the xoffset and yoffset as parameters. In this scenario, we are going to use 80 and 30.

    Finally, we can call the “perform” method to execute it.

    drag_and_drop_by_offset

    We will again locate an element “message”, that is shown inside the droparea with “Dropped!” text, when the WebElement is dropped. We can again use XPath to locate it and then assert that the presented message is correct.

    locate an element “message

    You can run your test in LambdaTest by just typing the below command, for example, for 01_double_click.py:

    01_double_click.py

    Attention Point 1: 01_double_click.py is the name of our file. You can adjust the filename that you created.

    If you’re a Python programmer looking to make a name for yourself in the automation testing domain, you can start by getting broad hands-on experience with Selenium Python 101 certification.

    Conclusion

    In this blog, we have learned about how to automate mouse clicks with Selenium Python.

    It was presented why using Python and Selenium for test automation. We showed what the ActionChains library is and how it helps you to automate mouse actions, and we presented all the available library methods.

    We also presented the setup process you should follow to configure all the required environments, including how to run automation tests on a cloud Selenium Grid using the LambdaTest platform.

    You could learn the most basic thing in Python web automation: how to open a webpage in Chrome. Finally, it was shown how to automate mouse action with Selenium Python through demonstration test scenarios.

    Frequently Asked Questions (FAQs)

    How do you perform mouse actions in Selenium Python?

    The simplest way to perform a mouse action is by using its corresponding method from ActionChains. These methods are: click(), double_click(), drag_and_drop(), get_attribute(), get_current_url(), get_title(), is_element_present(), move_to_element(), moveToElementWithId(), moveToElementWithText() and sendKeys().

    Can Selenium move mouse?

    The Actions class in Selenium WebDriver enables us to move the mouse pointer to a specific location or element. To create an object of the actions class, we have to use the WebDriver instance created by the webdriver.Create() method.
    The MoveToElement() method in the actions class takes the locator object as a parameter and moves it to that specific location/element. We can move one or more locations/elements using this method.

    Can Selenium click buttons?

    There are a variety of web page components that one can access while using the Selenium web driver. These include buttons, scroll bars, hyperlinks, etc

    Author Profile Author Profile Author Profile

    Author’s Profile

    Paulo Oliveira

    Paulo is a Quality Assurance Engineer with more than 15 years of experience in Software Testing. He loves to automate tests for all kind of applications (both backend and frontend) in order to improve the team’s workflow, product quality, and customer satisfaction. Even though his main roles were hands-on testing applications, he also worked as QA Lead, planning and coordinating activities, as well as coaching and contributing to team member’s development. Sharing knowledge and mentoring people to achieve their goals make his eyes shine.

    Blogs: 12



    linkedintwitter

    Test Your Web Or Mobile Apps On 3000+ Browsers

    Signup for free