XPath Functions Used in Selenium Projects
XPath functions make locators more flexible and dynamic, handling elements with partial or changing attribute values.
1. contains() — Partial attribute match: Matches elements where the attribute contains a given substring.
// Find element where id contains "log"
driver.findElement(By.xpath("//*[contains(@id, 'log')]"));
// Find button where text contains "Sign"
driver.findElement(By.xpath("//button[contains(text(), 'Sign')]"));
// Dynamic class name
driver.findElement(By.xpath("//div[contains(@class, 'nav-item')]"));
2. text() — Match by visible text: Matches elements with exact or partial visible text.
// Exact text match
driver.findElement(By.xpath("//a[text()='Click Here']"));
// With contains for partial text
driver.findElement(By.xpath("//p[contains(text(), 'Welcome')]"));
// Heading with specific text
driver.findElement(By.xpath("//h2[text()='Login']"));
3. starts-with() — Match beginning of attribute: Useful when an attribute starts with a known prefix but ends dynamically.
// ID starts with "user_"
driver.findElement(By.xpath("//*[starts-with(@id, 'user_')]"));
// Name attribute starts with "login"
driver.findElement(By.xpath("//input[starts-with(@name, 'login')]"));
4. OR operator (|) — Multiple conditions: Match elements that satisfy either condition.
// Element with class "btn" OR id "submit"
driver.findElements(By.xpath("//*[@class='btn' or @id='submit']"));
// Multiple possible text values
driver.findElement(By.xpath("//button[text()='Login' or text()='Sign In']"));
5. AND operator — Multiple conditions: Match elements that satisfy all conditions.
// Input with type="text" AND placeholder="Username"
driver.findElement(By.xpath("//input[@type='text' and @placeholder='Username']"));
// Link with specific class AND text
driver.findElement(By.xpath("//a[@class='nav-link' and text()='Home']"));
Combined functions:
// contains + starts-with
driver.findElement(By.xpath("//input[starts-with(@id, 'user') and contains(@class, 'form')]"));
// Text with contains + and
driver.findElement(By.xpath("//div[@class='item' and contains(text(), 'Product')]"));
Quick reference:
| Function | Syntax | Use case |
|---|---|---|
contains() | contains(@attr, 'val') | Partial attribute value |
text() | text()='value' | Exact visible text |
starts-with() | starts-with(@attr, 'prefix') | Dynamic ID/name prefix |
or | @a='x' or @b='y' | Either condition |
and | @a='x' and @b='y' | Both conditions |
