</>

Technology

Selenium

Difficulty

Beginner

Interview Question

How can we locate elements using their text in XPath?

Use the text() function or contains(text()) in XPath to locate elements by their visible text content.

Answer

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 typeExactPartial
Dynamic textFailsWorks
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();

Follow AutomateQA

Related Topics