XPath functions (contains, starts-with) 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.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import java.time.Duration; public class LoginButtonXPathTest { private WebDriver driver; private WebDriverWait wait; @BeforeEach public void setUp() { driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.get("https://example.com/login"); } @Test public void testLoginButtonUsingXPathFunctions() { // Locate login button using contains() on class attribute By loginBtnContains = By.xpath("//button[contains(@class, 'btn-login')]"); WebElement buttonContains = wait.until(ExpectedConditions.visibilityOfElementLocated(loginBtnContains)); assertTrue(buttonContains.isDisplayed(), "Login button located by contains() should be displayed"); // Locate login button using starts-with() on id attribute By loginBtnStartsWith = By.xpath("//button[starts-with(@id, 'loginBtn')]"); WebElement buttonStartsWith = wait.until(ExpectedConditions.elementToBeClickable(loginBtnStartsWith)); assertTrue(buttonStartsWith.isEnabled(), "Login button located by starts-with() should be enabled"); } @AfterEach public void tearDown() { if (driver != null) { driver.quit(); } } }
This test uses Selenium WebDriver with Java to automate the manual test case.
In setUp(), we open the Chrome browser and navigate to the login page.
In the test method, we use By.xpath with contains() to find the login button by part of its class attribute. We wait explicitly until it is visible, then assert it is displayed.
Next, we use starts-with() to find the login button by the start of its id attribute. We wait until it is clickable, then assert it is enabled.
Finally, in tearDown(), we close the browser to clean up.
This approach uses explicit waits to avoid timing issues and uses clear assertions to verify the button's presence and state.
Now add data-driven testing with 3 different button class name fragments to locate the login button using contains()