How to Click Button With Selenium in Python

Manav Narula Feb 02, 2024
How to Click Button With Selenium in Python

We can use the selenium package in Python to automate tasks on almost all major web browsers. We can retrieve the elements, fill out forms, click buttons, and perform other such actions with this package.

This tutorial will demonstrate how to click a button on a web page with selenium in Python.

Click Button With Selenium in Python

We will start by importing the webdriver class and creating its object to initiate the connection and open a web browser. We will use this object to retrieve the required web page with its URL in the get() function.

First, we need to retrieve the required button element to click the button. This can be achieved in many ways.

We can retrieve the elements with attributes like name, class, id, and more with selenium.

After retrieving the element for the button, we will perform the action to click the button by using the click() function.

This logic is implemented in the code below.

from selenium import webdriver

driver = webdriver.Chrome(r"C:/path/to/chromedriver.exe")
driver.get("https://www.sample_website.org/")
e = driver.find_element_by_class_name("slide-out-btn")
e.click()

We use the webdriver class to open the Google Chrome browser in the above example. We redirect to the required website and use the find_element_by_class_name() function to get the element of the button.

After that, the click() function is used to click on the retrieved button.

Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python Selenium