Open In App

Python Selenium – Find Button by text

In this article, let’s discuss how to find a button by text using selenium. See the below example to get an idea about the meaning of the finding button by text.

Example:



URL: https://html.com/tags/button/

We need to find the “CLICK ME!” button using the text “Click me!”.



Module Needed:

Selenium: The selenium package is used to automate web browser interaction from Python. It is an open-source tool primarily used for testing. Run the following command in the terminal to install this library:

pip install selenium

Setup Web Drivers:

Web Driver is a package to interact with a Web Browser. You can install any Web Driver according to your browser choice. Install any one of them using the given links-

Firefox https://github.com/mozilla/geckodriver/releases
Safari https://webkit.org/blog/6900/webdriver-support-in-safari-10/
Chrome https://sites.google.com/a/chromium.org/chromedriver/downloads

Here, we are going to use ChromeDriver.

Find xpath of the button:

Approach:

Implementation:




# Import Library
from selenium import webdriver
import time
  
# set webdriver path here it may vary
# Its the location where you have downloaded the ChromeDriver
driver = webdriver.Chrome(executable_path=r"C:\\chromedriver.exe")
  
# Get the target URL
  
# Wait for 5 seconds to load the webpage completely
time.sleep(5)
  
# Find the button using text
driver.find_element_by_xpath('//button[normalize-space()="Click me!"]').click()
  
time.sleep(5)
  
# Close the driver
driver.close()

Output:


Article Tags :