Click the Button by Text Using Python and Selenium

Python and Selenium are two widely recognized and influential tools for web automation tasks, including testing, web scraping, and web interaction. Among the various tasks that web automation can perform, clicking a button on a webpage is one of the most common actions. The process of clicking a button on a webpage involves locating the button element using its text label.

In this article, we offer a comprehensive guide on how to automate the process of clicking a button on a webpage using Python and Selenium by identifying the button element through its text label. We will take you through the necessary steps to set up a Selenium environment, locate the button elements using various techniques, and perform the click action efficiently.

Prerequisites

Before getting started, ensure you have the following installed ?

# Install selenium using pip
# pip install selenium

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Setup Chrome driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()
print("Selenium WebDriver initialized successfully")
Selenium WebDriver initialized successfully

Method 1: Using XPath with Text Content

The most common approach is to use XPath to locate buttons by their text content ?

from selenium import webdriver
from selenium.webdriver.common.by import By

# Initialize driver
driver = webdriver.Chrome()

try:
    # Navigate to a sample page
    driver.get("data:text/html,<html><body><button>Click Me</button><button>Submit</button></body></html>")
    
    # Find button by exact text
    button = driver.find_element(By.XPATH, "//button[text()='Click Me']")
    button.click()
    print("Button clicked successfully using exact text match")
    
    # Find button by partial text
    submit_button = driver.find_element(By.XPATH, "//button[contains(text(),'Submit')]")
    submit_button.click()
    print("Submit button clicked using partial text match")
    
finally:
    driver.quit()
Button clicked successfully using exact text match
Submit button clicked using partial text match

Method 2: Using Link Text for Link Elements

For anchor tags (<a>), you can use the link text locators ?

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

try:
    # Navigate to a sample page with links
    html_content = """
    <html><body>
    <a href="#">Full Link Text</a>
    <a href="#">Partial Link Example</a>
    </body></html>
    """
    driver.get(f"data:text/html,{html_content}")
    
    # Click by exact link text
    driver.find_element(By.LINK_TEXT, "Full Link Text").click()
    print("Clicked using LINK_TEXT")
    
    # Click by partial link text
    driver.find_element(By.PARTIAL_LINK_TEXT, "Partial Link").click()
    print("Clicked using PARTIAL_LINK_TEXT")
    
finally:
    driver.quit()
Clicked using LINK_TEXT
Clicked using PARTIAL_LINK_TEXT

Method 3: Using WebDriverWait for Dynamic Content

For pages where elements load dynamically, use explicit waits ?

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()

try:
    # Navigate to page
    driver.get("data:text/html,<html><body><button id='dynamic-btn'>Dynamic Button</button></body></html>")
    
    # Wait for button to be clickable
    wait = WebDriverWait(driver, 10)
    button = wait.until(
        EC.element_to_be_clickable((By.XPATH, "//button[contains(text(),'Dynamic Button')]"))
    )
    button.click()
    print("Dynamic button clicked after waiting")
    
except Exception as e:
    print(f"Error: {e}")
    
finally:
    driver.quit()
Dynamic button clicked after waiting

Comparison of Methods

Method Use Case Pros Cons
XPath with text() Exact text match Precise matching Breaks if text changes
XPath with contains() Partial text match More flexible May match unintended elements
LINK_TEXT Anchor elements Built-in Selenium method Only works with <a> tags
WebDriverWait Dynamic content Handles timing issues Requires additional setup

Best Practices

When clicking buttons by text, follow these recommendations ?

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def click_button_by_text(driver, button_text, timeout=10):
    """
    Robust function to click button by text with error handling
    """
    try:
        # Wait for element to be clickable
        wait = WebDriverWait(driver, timeout)
        button = wait.until(
            EC.element_to_be_clickable((By.XPATH, f"//button[contains(text(),'{button_text}')]"))
        )
        button.click()
        return True
    except Exception as e:
        print(f"Failed to click button '{button_text}': {e}")
        return False

# Example usage
driver = webdriver.Chrome()
try:
    driver.get("data:text/html,<html><body><button>Submit Form</button></body></html>")
    
    success = click_button_by_text(driver, "Submit Form")
    if success:
        print("Button clicked successfully")
    else:
        print("Button click failed")
        
finally:
    driver.quit()
Button clicked successfully

Conclusion

Clicking buttons by text using Python and Selenium is a powerful technique for web automation. Use XPath with contains() for flexibility, implement WebDriverWait for dynamic content, and always include proper error handling. Choose the method that best fits your specific use case and webpage structure.

Updated on: 2026-03-27T09:02:05+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements