XPath with text() helps find web elements by matching their visible text. This makes locating elements easier when you know the exact text shown on the page.
0
0
XPath with text() in Selenium Python
Introduction
You want to click a button or link with a specific label.
You need to verify that a message or heading with exact text appears on the page.
You want to find a list item or paragraph by its visible text.
You are testing a page where element IDs or classes are dynamic but text is stable.
Syntax
Selenium Python
//tagname[text()='exact text']Replace tagname with the HTML element name like button, a, or div.
The text inside text()='...' must match exactly, including spaces and case.
Examples
Selects a
button element whose visible text is exactly 'Submit'.Selenium Python
//button[text()='Submit']Selects a link (
a) with the text 'Home'.Selenium Python
//a[text()='Home']Selects a paragraph with the exact welcome message.
Selenium Python
//p[text()='Welcome to our site!']Sample Program
This script opens a simple HTML page with buttons, a link, and a paragraph. It uses XPath with text() to find elements by their visible text and prints their text content.
Selenium Python
from selenium import webdriver from selenium.webdriver.common.by import By # Setup WebDriver (make sure driver executable is in PATH) driver = webdriver.Chrome() # Open a simple test page html = ''' <html> <body> <button>Submit</button> <button>Cancel</button> <a href='#'>Home</a> <p>Welcome to our site!</p> </body> </html> ''' # Load the HTML content using data URL driver.get('data:text/html;charset=utf-8,' + html) # Find the Submit button using XPath with text() submit_button = driver.find_element(By.XPATH, "//button[text()='Submit']") print('Submit button text:', submit_button.text) # Find the Home link home_link = driver.find_element(By.XPATH, "//a[text()='Home']") print('Home link text:', home_link.text) # Find the paragraph welcome_para = driver.find_element(By.XPATH, "//p[text()='Welcome to our site!']") print('Paragraph text:', welcome_para.text) # Close the browser driver.quit()
OutputSuccess
Important Notes
Text matching with text() is exact. Use functions like contains() if partial matching is needed.
Whitespace and case must match exactly when using text().
Using text() is helpful when element attributes are not reliable or missing.
Summary
XPath with text() finds elements by their exact visible text.
It is useful for buttons, links, and messages where text is stable.
Remember to match text exactly, including spaces and case.