XPath Text and Contains Functions

Matching Visible Text

<button class="btn">  Add to Cart  </button>
<p class="error-message">Invalid email or password. Attempts left: 2</p>
<a href="/offers">Today's Offers</a>
XPathMatches
//a[text()="Today's Offers"]exact text (use double quotes inside when the text has an apostrophe)
//button[normalize-space()='Add to Cart']text with extra spaces trimmed
//p[contains(text(),'Invalid email')]part of the text
//p[contains(@class,'error')]part of an attribute
//a[starts-with(@href,'/off')]attribute starts with

Example

WebElement error = driver.findElement(By.xpath("//p[contains(text(),'Invalid email')]"));
System.out.println(error.getText());

Example

Output:

Run LoginErrorTest.main()

Example output

Invalid email or password. Attempts left: 2

Tip: contains() is the most used XPath function in real projects, because messages often have changing parts like "Attempts left: 2".