XPath with text() in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.time.Duration; public class XPathTextTest { private WebDriver driver; private WebDriverWait wait; @BeforeClass public void setUp() { // Set path to chromedriver if needed driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.get("https://example.com/sample-buttons"); // Replace with actual URL } @Test public void testClickSubmitButtonUsingXPathText() { // Locate the button with exact text 'Submit' using XPath with text() By submitButtonLocator = By.xpath("//button[text()='Submit']"); // Wait until the button is clickable WebElement submitButton = wait.until(ExpectedConditions.elementToBeClickable(submitButtonLocator)); // Verify the button is displayed Assert.assertTrue(submitButton.isDisplayed(), "Submit button should be visible"); // Click the button submitButton.click(); // Verify expected result - for example, URL changed or confirmation message displayed // Here we check URL contains 'submitted' as an example wait.until(ExpectedConditions.urlContains("submitted")); String currentUrl = driver.getCurrentUrl(); Assert.assertTrue(currentUrl.contains("submitted"), "URL should contain 'submitted' after clicking Submit"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
This test script uses Selenium WebDriver with Java and TestNG framework.
Setup: The @BeforeClass method initializes the ChromeDriver and opens the sample page.
Test: We locate the 'Submit' button using XPath with the text() function: //button[text()='Submit']. We use an explicit wait to ensure the button is clickable before interacting.
We assert the button is visible, then click it. After clicking, we wait for the URL to contain the word 'submitted' to confirm the expected page change.
Teardown: The @AfterClass method closes the browser to clean up.
This approach ensures the test is stable, readable, and follows best practices like explicit waits and proper assertions.
Now add data-driven testing to click buttons with text 'Submit', 'Cancel', and 'Reset' using XPath with text()
Practice
//button[text()='Submit'] select in a web page?Solution
Step 1: Understand the XPath syntax
The expression//buttonselects all button elements in the document.Step 2: Apply the
The predicatetext()condition[text()='Submit']filters those buttons to only those whose visible text exactly matches 'Submit'.Final Answer:
A button element with the exact visible text 'Submit' -> Option AQuick Check:
XPath with text() = exact text match [OK]
- Confusing attribute text with text() function
- Assuming partial text match without contains()
- Selecting wrong element types
<a>) with visible text exactly 'Home'?Solution
Step 1: Identify exact text match syntax
The correct syntax for exact text match usestext()='Home'inside brackets.Step 2: Check each option
//a[contains(text(), 'Home')] uses contains(), which is partial match, not exact. //a[text()='home'] has wrong case 'home' (case-sensitive). //a[@text='Home'] incorrectly treats text as attribute.Final Answer:
//a[text()='Home'] -> Option AQuick Check:
Exact text match uses text()='value' [OK]
- Using contains() when exact match is needed
- Ignoring case sensitivity in text()
- Treating text as an attribute
<div> <button>Save</button> <button>Cancel</button> <button>Save As</button> </div>
What will the XPath
//button[text()='Save'] select?Solution
Step 1: Understand exact text() matching
The XPathtext()='Save'matches only buttons whose visible text is exactly 'Save'.Step 2: Analyze the buttons' text
Only the first button has exactly 'Save'. The third button's text is 'Save As', which does not match exactly.Final Answer:
The first button with text 'Save' only -> Option DQuick Check:
text()='Save' matches exact text only [OK]
- Assuming partial match with text()
- Selecting multiple elements incorrectly
- Ignoring spaces or extra words
//label[text()='username']. It does not find the element. What is the likely problem?Solution
Step 1: Check case sensitivity in XPath text()
XPath text() matching is case-sensitive, so 'username' does not match 'Username'.Step 2: Verify other options
text() works with any element, contains() is optional, and @text is invalid attribute syntax.Final Answer:
XPath is case-sensitive; 'username' does not match 'Username' -> Option BQuick Check:
XPath text() is case-sensitive [OK]
- Ignoring case sensitivity
- Using attribute syntax instead of text()
- Assuming text() only works on certain tags
<span> element that contains the exact text 'Error: Invalid input' but the page sometimes adds extra spaces before or after the text. Which XPath expression is best to handle this?Solution
Step 1: Understand the problem with extra spaces
Extra spaces before or after text cause exact text() match to fail.Step 2: Use normalize-space() to trim spaces
Usingnormalize-space(text())='Error: Invalid input'trims spaces and matches exact text.Step 3: Evaluate other options
//span[text()='Error: Invalid input'] fails with spaces, //span[contains(text(), 'Error: Invalid input')] matches partial text (not exact), //span[@text='Error: Invalid input'] is invalid syntax.Final Answer:
//span[normalize-space(text())='Error: Invalid input'] -> Option CQuick Check:
normalize-space() trims spaces for exact text match [OK]
- Using text() without trimming spaces
- Using contains() when exact match needed
- Treating text as attribute
Ready to prove it?
Pass the test and this pattern moves unknown
