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()