How to Use Selenium Click Commands Using Python

Paulo Oliveira

Posted On: July 18, 2024

view count496884 Views

Read time19 Min Read

Automating mouse clicks is essential for browser automation, allowing testers and developers to simulate real user interactions on web pages. Selenium, a powerful web automation tool combined with Python, offers a robust framework for automating these interactions. By automating Selenium click commands with Python, you can streamline testing processes, enhance accuracy, and save time by effortlessly executing repetitive tasks.

What Are Selenium Click Commands?

The Selenium click command automates your web application’s UI. Some of the Selenium click commands include:

  • click(): Performs a click operation on an element.
    Syntax: click(element)
  • click_and_hold(): Acts as holding the left mouse button to an element.
    Syntax: click_and_hold(element)
  • context_click(): Performs a right-click operation on an element.
    Syntax: context_click(element)
  • double_click(): Performs a double-click operation on an element.
    Syntax: double_click(element)
  • drag_and_drop(): It holds the left mouse button on the source element. Then, it moves to the target element and finally releases the mouse button.
    Syntax: drag_and_drop(element, target)
  • drag_and_drop_by_offset(): Description: It holds the left mouse button on the source element. Then, it moves to the target offset and finally releases the mouse button.

    Syntax: drag_and_drop_by_offset (element, xoffset, yoffset)

  • move_by_offset(): Performs movement of the mouse to an offset from the present position of the mouse.
    Syntax: move_by_offset(xoffset, yoffset)
  • move_to_element(): Performs mouse movement to the middle of the element.
    Syntax: move_to_element(element)
  • move_to_element_with_offset(): Performs mouse movement by offsetting 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)

These commands, provided by Selenium WebDriver, help simulate Selenium click operations on WebElements like buttons, links, and more. However, you can also perform complex actions like drag and drop, click and hold, etc., using Selenium’s ActionChains library, thus enhancing your web automation scripts with precise and efficient interactions.

What Is ActionChains?

ActionChains is a Python library that automates special interactions such as context click, double click, drag and drop mouse movements, and key down and up actions. It 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 want to show you how to create an object using the ActionChains library.

To use the ActionChains library, import it and instantiate an object by passing the browser element where actions will be executed. ActionChains supports various mouse actions, which we will learn further in this blog on Selenium click.

On a side note, you can further enhance your Selenium automation testing by leveraging AI testing agents like KaneAI.

KaneAI is a smart AI test assistant for high-speed quality engineering teams. With its unique AI-driven features for test authoring, management, and debugging, KaneAI allows teams to create and evolve complex test cases using natural language.

How to Perform Selenium Clicks?

You can perform mouse actions on a web page using various Selenium click commands. In this section, we will learn about different Selenium click commands with demonstrations, each executed on a cloud-based platform.

Before learning to implement the various Selenium click commands, you must gather the required libraries and necessary development tools.

Prerequisites:

To start the coding, you must follow the steps to set up Python, Selenium, and Visual Studio Code.

  1. First, you must download and install Python according to your operating system.
  2. 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. Use the following command before installing Selenium WebDriver.
  3. Quick Note: ActionChains is installed within the Selenium WebDriver library, so you just need to use it.

  4. Download and install the Visual Studio Code, one of the most used IDEs. For the coding demonstration, we will be using Visual Studio Code. You can use your preferred IDE;

Executing multiple tests in parallel on a local machine can be challenging due to limited resources and a lack of proper infrastructure. Using a cloud-based platform provides a ready-to-use test infrastructure, eliminating the need for frequent environment setups.

One such cloud platform is LambdaTest, an AI-powered test execution platform that provides a stable test infrastructure, allowing you to run manual and automated tests at scale with over 3000+ real devices, browsers, and OS combinations.

Once you have downloaded the required libraries and IDEs, you must use the capabilities to configure the environment where the test will run to use the LambdaTest cloud grid in your code. These capabilities will enable you to select the browser, browser version, and OS, capture logs, record tests, and more during the test execution.

Follow the steps below to get started with LambdaTest:

  1. Create an account on the LambdaTest platform.
  2. Obtain your LambdaTest Username and Access Key: Navigate to Profile > Account Settings > Password & Security tab.
  3. Update the required capabilities: Use the LambdaTest Capabilities Generator to select and generate the necessary code for the desired capabilities.

Lambdatest configuration steps diagram

By following these steps, you’ll be set up to run your tests on LambdaTest with the appropriate configurations.

We are now prepared to execute various mouse click methods. To perform each mouse action method, we will use Selenium 4 on Windows 11, executing the tests on the latest version of the Chrome browser with a resolution of 1024×768.

We will further learn how to automate Selenium click commands, each based on specific test scenarios.

Below are the supported Selenium click commands that help you deal with various mouse operations:

Performing Single Click in Selenium

In this section, we will learn how to implement the click() method in Selenium Python to perform a single click.

To better understand the workings of the Selenium click() method, let’s take a test scenario to demonstrate its functionality.

Test Scenario:

  1. Open LambdaTest Selenium Playground.
  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, as shown below.

Screenshot of LambdaTest Selenium Playground with an example automation test scenario

Code Implementation:

Below is the code implementation of the above test scenario.

Code Walkthrough:

In the above code, you must locate the form’s message field, the button, and the “your message” area. These fields can be located by ID, making the code simpler.

Diagram showing the form's message field, button, and 'your message' area for a code walkthrough

To perform the click() operation, you must create an ActionChains object to interact with elements.

The first action will be to click on the message field for which you must use the click() method, and the on_element parameter should reference the message_field variable.

The second action will be to type ‘Hello!’ into the field. You can do this using the send_keys method.

The third step will be to click on the button.

Finally, you must call the perform() method.

actionchains-object-usage-in-selenium-for-clicking-on-a-message-field-typing-hello-and-clicking-a-button

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

Finally, you call browser.quit() to close the browser instance.

Before we learn other Selenium click methods, the code for locating the message field in the form, initializing the browser, sending keys and assertions, using the perform() method, and quitting the browser remains unchanged. Hereafter, we will only highlight the code for performing specific Selenium click commands for mouse actions.

Performing Click and Hold in Selenium

Let’s learn how to implement Selenium click_and_hold() and release() methods using Python.

Here, we will use the Selenium click command to click on a WebElement in the DOM, hold it, and then release it. This involves using the click_and_hold(element) and release() methods of ActionChains.

To better understand the workings of the click_and_hold(element) and release() method, let’s take a test scenario to demonstrate its functionality.

  1. Open LambdaTest Selenium Playground.
  2. Click in the message field.
  3. Write “Hello!” in the message field.
  4. Click and Hold the button “Get Checked Value”.
  5. Release the button.
  6. Check that the message is presented as “Hello!”.

You can view the page where we will automate some actions, as shown below.

Screenshot of the LambdaTest Selenium Playground page for demonstrating the click_and_hold() and release() methods in Selenium with Python

Code Implementation:

Below is the code implementation of the above test scenario.

Code Walkthrough:

The code that is responsible for performing click_and_hold() is given below.

Code snippet demonstrating the use of click_and_hold() method in Selenium WebDriver

Once you perform the click_and_hold() method, you can release() the mouse action using the release() method.

Mouse click and hold action followed by release

Finally, you must call the perform() method to help you perform your code instructions and then use the browser.quit(), close the browser instance.

Performing Context Click in Selenium

Let’s learn how to implement the Selenium content_click() method using Python.

Here, we will use the Selenium click command to right-click on a WebElement in the DOM. This involves using the context_click(element) method of ActionChains.

To better understand the workings of the context_click(element) method, let’s take a test scenario to demonstrate its functionality.

Test Scenario:

  1. Open LambdaTest Selenium Playground.
  2. Click in the message field.
  3. Perform a right mouse click (context_click).

You can view the screenshot of the page below, where we will automate context click action.
Screenshot demonstrating context click automation action on webpage

Code Implementation:

Below is the code implementation of the above test scenario.

Code Walkthrough:

As you can see, the code remains the same; the only action will be to click the right mouse button and type “Hello!” We can do this in the field using the context_click() method.

Demonstration of context_click() method usage in code walkthrough

Finally, you must call the perform() method to help you perform your code instructions and then use the browser.quit() to close the browser instance.

Performing Double Click in Selenium

Let’s learn how to implement the Selenium double_click() method using Python.

Here, we will use the Selenium click command to double-click on a WebElement in the DOM. This involves using the double_click(element) method of ActionChains.

To better understand the workings of the double_click(element) method, let’s take a test scenario to demonstrate its functionality.

Test Scenario:

  1. Open LambdaTest Selenium Playground.
  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 screenshot of the page below, where we will automate the double-click action.

Screenshot of LambdaTest Selenium Playground showing automation of double-click action on Age column title

Code Implementation:

Code Walkthrough:

The first part of the script will be the necessary code to open the desired web page, as shown in the previous section of this blog on automating Selenium click commands using Python.

automating Selenium click commands using Python

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

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

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

find the Age column title element

The element is shown in the details below. We can locate this element using the

element, which has the aria-label attribute with the Age: activate to sort column ascending value. You must store the element in a variable called age_sorting.

The code for locating the element is shown below.

<th class=”sorting” tabindex=”0″ aria-controls=”example” rowspan=”1″ colspan=”1″ aria-label=”Age: activate to sort column ascending” style=”width: 81.3px;”>Age</th>

Age: activate to sort column ascending

Then, use the ActionChains method double_click(), specifying the element to be double-clicked and stored in the age_sorting variable.

age_sorting variable

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.

first two lines using XPath again

Then, we can finally assert that first_age equals “66” and second_age equals “64”.

 first_age equals “66” and second_age equals “64”

Finally, you must call the perform() method to help you perform your code instructions and then use the browser.quit(), close the browser instance.

Performing Drag and Drop in Selenium

Let’s learn how to implement the Selenium drag_and_drop() method using Python.

Here, we will use the Selenium click command to drag a WebElement in the DOM to a specific target element. This involves using the drag_and_drop(element, target) method of ActionChains.

To better understand the workings of the drag_and_drop(element, target) method, let’s take a test scenario to demonstrate its functionality.

Test Scenario:

  1. Open the LambdaTest Selenium Playground.
  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 screenshot of the page below, where we will automate drag and drop action.

drag and drop action

Code Implementation:

Below is the code implementation of the above test scenario.

Code Walkthrough:

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

element in “draggable” and “droparea” variables

To drag and drop the element, you must call the drag_and_drop() method, passing the “draggable” and “droparea” variables as parameters.

Finally, you must call the perform() method to help you perform your code instructions.

drag_and_drop() method

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

locate an element “message”

Once the element is dropped, use the assert methods to compare the actual text with the expected text and then use the browser.quit(), close the browser instance.

To learn how to use asserts correctly, follow this blog on using asserts in Selenium WebDriver.

Performing Drag and Drop by Offset in Selenium

Let’s learn how to implement the Selenium drag_and_drop_by_offset() method using Python.

Here, we will use the Selenium click command to drag a WebElement in the DOM to a specific target offset. This involves using the drag_and_drop_by_offset(element, xoffset, yoffset) method of ActionChains.

To better understand the workings of the drag_and_drop_by_offset(element, xoffset, yoffset) method, let’s take a test scenario to demonstrate its functionality.

Test Scenario:

  1. Open the LambdaTest Selenium Playground (Drag and Drop).
  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 screenshot of the page below, where we will automate drag and drop by offset action.

Check that the “Drop Here” message changes to “Dropped

Code Implementation:

Below is the code implementation of the above test scenario.

Code Walkthrough:

In this test scenario, we must again locate the draggable WebElement. We can use XPath again and store the element in the “draggable” variable.

 locate the draggable WebElemen

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 will use the 80 and 30 offsets.

Finally, you must call the perform() method to help you perform your code instructions.

call the perform()

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.

“Dropped!” text when the WebElement is dropped

Once the element is dropped, use the assert methods to compare the actual text with the expected text and then use the browser.quit(), close the browser instance.

Performing Move by Offset in Selenium

Let’s learn how to implement the Selenium move_by_offset() method using Python.

Here, we will use the Selenium click command to move the mouse by offsetting the current mouse position. This involves using the move_by_offset(xoffset, yoffset) method of ActionChains.

To better understand the workings of the drag_and_drop_by_offset(element, xoffset, yoffset) method, let’s take a test scenario to demonstrate its functionality.

Test Scenario:

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

You can view the screenshot of the page below, where we will automate move by offset action.

 text “Hover” is shown

Code Implementation:

Below is the code implementation of the above test scenario.

Code Walkthrough:

To move the mouse cursor to a specific offset position, you must call the move_by_offset() method, passing the two offset values. In this example, we will use 617 to offset and 593 to offset. Call the perform() method to help you perform your code instructions.

move_by_offset()

Use the assert methods to compare the actual text with the expected text and then use the browser.quit(), close the browser instance.

Performing Move to Element in Selenium

Let’s learn how to implement the Selenium move_to_element() method using Python.

Here we will use the Selenium click command to move the mouse to a WebElement in the DOM. This involves using the move_to_element(element) method of ActionChains.

To better understand the workings of the move_to_element(element) method, let’s take a test scenario to demonstrate its functionality.

Test Scenario:

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

You can view the screenshot of the page below, where we will automate the move to element action.

text “Hover” is shown

Code Implementation:

Below is the code implementation of the above test scenario.

Code Walkthrough:

In this test scenario, you must locate the first image on the page after configuring the capabilities to access the page. You can use XPath again and store the element in the “first_image” variable.

“first_image” variable

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, you must call the perform() method to help you perform your code instructions.

move_to_element()

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

“Hover” text when the mouse is on the image

Then, use the assert methods to compare the actual text with the expected text and then use the browser.quit(), close the browser instance.

Performing Move to Element With Offset in Selenium

Let’s learn how to implement the Selenium move_to_element_with_offset() method using Python.

Here, we will use the Selenium click commands to perform mouse movement by offsetting the specified WebElement in the DOM. This involves using the move_to_elemenet_with_offset(element, xoffset, yoffset) method of ActionChains.

To better understand the workings of the move_to_elemenet_with_offset(element, xoffset, yoffset) method, let’s take a test scenario to demonstrate its functionality.

Test Scenario:

  1. Open LambdaTest Selenium Playground (Mouse Hover).
  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 view the screenshot of the page below, where we will automate moving to the element with offset action.

automate moving to the element with offset action

Code Implementation:

Below is the code implementation of the above test scenario.

Code Walkthrough:

In this test scenario, we must locate the first image on the page. We can use XPath again and store the element in the “first_image” variable.

“first_image” variable

Then, to move the mouse cursor to the first image, you must call the move_to_element_with_offset() method, passing the “first_image” variable as a parameter and the two offset values. In this example, we have used 100 to xoffset and 200 to yoffset.

Finally, you must call the perform() method to help you perform your code instructions.

move_to_element_with_offset()

We will again locate an element “message” 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.

“Hover” text when the mouse

Then, use the assert methods to compare the actual text with the expected text and then use the browser.quit(), close the browser instance.

Generally, to run each of the tests above, use the following command

python filename.py

Once you run the above command, you will see the result in the console if the console is as shown below:

 result in the console

This means the test was run successfully. You can access the LambdaTest Dashboard page to see the execution steps and watch the video record of the script running.

LambdaTest Dashboard page

To learn more about other Selenium methods around keyword and mouse actions, follow this blog on Actions class in Selenium and get detailed insights.

You can also Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorials around Selenium testing, Selenium with Java, and more.

Conclusion

We learned how to automate Selenium click commands using Python. We discussed the benefits of using Python and Selenium for test automation, introduced the ActionChains library, and explained how it facilitates mouse actions. We also covered the setup process for configuring the required environments, including running automation tests on a cloud Selenium Grid using the LambdaTest platform.

Additionally, we covered the basics of Python web automation, such as opening a webpage in Chrome. Finally, we demonstrated how to automate mouse actions with Selenium and Python through various test scenarios.

Frequently Asked Questions (FAQs)

How do you perform mouse actions in Selenium Python?

The simplest way to perform a mouse action is using the corresponding ActionChains method. 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 the 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: 15



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free