How to Automate Click Using Selenium WebDriver?
Last Updated :
04 Oct, 2024
Selenium is one of the most popular and powerful tools for automating web applications. Selenium is widely used for automating user interactions like filling out forms, clicking on a button, navigating to a web page, and many more. One of the most common tasks while working with Selenium is clicking on an element as it is widely used for interacting with a web application. So in this article, we'll learn how to click on an element using Selenium Web Driver.
- Selenium can automatically click on buttons that appear on a webpage.
- We can find the button on the web page by using methods like find_element_by_class_name(), find_element_by_name(), find_element_by_id() etc, following which we can click on it by using the click() method.
# finding the button using ID
button = driver.find_element_by_id(ID)
# clicking on the button
button.click()
Syntax:
Python
import time
# importing webdriver from selenium
from selenium import webdriver
# Here Chrome will be used
driver = webdriver.Chrome()
# URL of website
url = "https://www.geeksforgeeks.org/"
# Opening the website
driver.get(url)
# getting the button by class name
button = driver.find_element_by_class_name("slide-out-btn")
# clicking on the button
button.click()
Output:
This will click on the button and a popup will be shown.
Steps of Automation on "Click" element using Selenium WebDriver
While working with Selenium Web Driver one of the most common tasks we see is clicking on an element.
Step 1: Setting up the Selenium in Python.
Make sure to install Python in your system then we'll install Selenium using the following command in the terminal.
pip install Selenium
Step 2: Installing the necessary modules.
Now that we have installed Selenium we'll need to import Web Driver and By from Selenium.
- WebDriver: Web Driver is an important part of Selenium, it provides a way to interact with the web browser programmatically. It acts as a bridge between our automation script and the Web Browser
- By: By is a class in Selenium that provides a way to locate an element on a web page using various locating Strategies.
from selenium import webdriver
from selenium.webdriver.common.by import By
Step 3: Initializing the Web Driver and navigating to the web page.
Now that we have imported the required modules we will create an instance of the web driver and navigate to the web page.
Explanation:
webDriver.Chrome() is used to create an instance of the Selenium Web Driver and select Chrome as our automation Web Browser. driver.get(url) is a method of selenium web driver which is used to navigate to the specified url.
Python
from selenium import webdriver
from selenium.webdriver.common.by import By
driver=webdriver.Chrome()
url="http://127.0.0.1:5500/index.html"
driver.get(url)
Step 4: Finding an element.
In order to click on an element we first need to find an element on a webpage using Selenium Web Driver using find_element() method and BY.
- find_element()- find_element is a method in Selenium which is used to find an element using a locating Strategy. It return an instance of the element if found .
- By- By is a class in Selenium which provides a way to locate an element on web page.
Python
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
url = "http://127.0.0.1:5500/index.html"
driver.get(url)
name_input = driver.find_element(By.NAME, "name")
Output:
Output of click on element using Selenium WebDriverNote: Here we have used name locating strategy to locate an element by its name attribute. Refer to Locating Strategies in Selenium to know more about locating Strategies.
Step 5: Click on an element.
- Now that we have locate the element we can now used .click() element to click on an element on a web page.
- .click(): It is a method in Selenium which is used to click on an element on a web page.
Python
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
url = "http://127.0.0.1:5500/index.html"
driver.get(url)
name_input = driver.find_element(By.NAME, "name")
name_input.click()
Output:
Output click on an element using Selenium WebDriverAdvanced Click Techniques - Using send_keys()
with Keys.CONTROL
This approach simulates a right-click using keyboard keys (typically Ctrl
+ Enter
). However, it's less reliable and might not work on all websites or browsers. Use it with caution and consider context_click()
as the primary method.
Python
print("GFG")
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get("https://geeksforgeeks.com")
element = driver.find_element_by_id("right_click_menu")
element.send_keys(Keys.CONTROL + Keys.RETURN)
driver.quit()
By understanding these techniques and their use cases, you can effectively perform right-click operations on elements in your Selenium tests.
Conclusion
Selenium is a powerful tool for automating web applicating and knowing how to click on an element using selenium is a fundamental skill for web automation and testing. Throughout the article, we have learned the important steps, from setting up Selenium and importing the necessary modules to navigating the website, finding the element on a web page, and clicking on the element. But we have to keep in mind that web applications are dynamic and we may need to adapt our code to handle various scenarios and changes in web structure.
Python
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://geeksforgeeks.com")
element = driver.find_element_by_id("my_button")
element.click()
driver.quit()
Are there ways to click other than a simple left-click?
Yes! Selenium allows you to simulate different click actions:
- Right-click: Use the
context_click()
method from ActionChains
. - Double-click: Create an
ActionChains
object and use the double_click()
method.
Python
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get("https://geeksforgeeks.com")
element = driver.find_element_by_id("context_menu_button")
actions = ActionChains(driver)
actions.context_click(element).perform()
driver.quit()
What if the element I want to click is hidden or not clickable?
In such cases, using click()
might not work. You might need to:
- Make the element visible: Use JavaScript with
JavascriptExecutor
to manipulate the element's style (e.g., change display: none
to display: block
). - Wait for the element to become clickable: Use explicit waits (e.g.,
WebDriverWait
with ExpectedConditions
) to ensure the element is ready before clicking.
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is a Neural Network?
Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read
Use Case Diagram - Unified Modeling Language (UML)
A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
9 min read