Click Button by Text – Python & Selenium

Selenium is an open source tool that automates web browsers and is widely used for automated testing of web applications.

With Python and Selenium you can easily create a script that searches a web-page for a button containing a particular text and clicks on it.

This note shows an example of how to find a button by text and click on it using Selenium and Python.

Cool Tip: How to automate login to a website using Selenium in Python! Read More →

Click Button by Text

In nutshell, to find a button by text and click on it, use the following structure:

button = driver.find_element(By.XPATH, '//button[text()="Button Text"]')

Complete Example

Create a project’s working directory:

$ mkdir -p ~/projects/click-button-by-text

Inside the project’s working directory create and activate a virtual environment:

$ cd ~/projects/click-button-by-text
$ python3 -m venv venv
$ . venv/bin/activate

Install Selenium:

$ pip install selenium webdriver_manager
$ pip show selenium | grep -i version
Version: 4.4.0
$ pip show webdriver_manager | grep -i version
Version: 3.8.3

Download and unzip the latest stable version of a ChromeDriver (the executable that Selenium uses to interact with Chrome):

$ sudo unzip ~/Downloads/ -d /usr/local/bin
$ chromedriver --version
ChromeDriver 104.0.5112.79

Create a file with the contents as follows:

# by

from selenium import webdriver
from import Service
from import By

driver = webdriver.Chrome(service=Service('/usr/local/bin/chromedriver'))

#Click on the button
button = driver.find_element(By.XPATH, '//button[text()="Click on Me"]')

Execute the to open the https://example.tld and click on the button containing the Click on Me text:

$ python

Cool Tip: How to add random delays in Python to not get banned! Read More →

Leave a Reply