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"]')
button.click()

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/chromedriver_linux64.zip -d /usr/local/bin
$ chromedriver --version
ChromeDriver 104.0.5112.79

Create a click_button_by_text.py file with the contents as follows:

# click_button_by_text.py
# by www.ShellHacks.com

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

driver = webdriver.Chrome(service=Service('/usr/local/bin/chromedriver'))
driver.get('https://example.tld')

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

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

$ python click_button_by_text.py

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

Leave a Reply