Use the text() function in XPath to locate elements by their visible text.
Exact text match:
XPATH
//button[text()=''Submit'']
//h1[text()=''Welcome'']
//a[text()=''Click Here'']
Partial text match using contains():
XPATH
//button[contains(text(),''Submit'')]
//span[contains(text(),''Error'')]
//div[contains(text(),''Success'')]
Difference:
text() | contains(text()) | |
|---|---|---|
| Match type | Exact | Partial |
| Dynamic text | Fails | Works |
| Example | [text()=''Login''] | [contains(text(),''Log'')] |
Important note:
text() is case-sensitive:
XPATH
//button[text()=''submit''] -- Will NOT match ''Submit''
Java code example:
Java
WebElement btn = driver.findElement(By.xpath("//button[text()=''Login'']"));
btn.click();
