How to findElement() by text in XPath?
Hey Mark,
To findElement() by text in XPath, we can use the findElement() method with the XPath locator for an exact match.
WebElement by XPath = driver.findElement(By.xpath("//*[text()='Exact Text']"));
If the exact WebElement text is unavailable, use the contains() function to check for partial matches to locate the WebElement.
WebElement byXPathWithContains = driver.findElement(By.xpath("//*[contains(text(),'Partial Text')]"));
To learn more about how to findElement() by text in Selenium using different methods, follow this guide below.
Hello Mark,
Here is the answer :-
The normalize-space()
function removes leading and trailing whitespace from a string and replaces sequences of whitespace characters with a single space. This XPath expression compares the normalized text of each element with the specified text.
Using Normalize-Space Function:
XPath: //*[normalize-space(text())=‘Your Text Here’] Explanation: The normalize-space() function removes leading and trailing whitespace from a string and replaces sequences of whitespace characters with a single space. This XPath expression compares the normalized text of each element with the specified text
Hello Mazay,
I hope this answer will works for you,
Using Normalize-Space Function:
XPath: //*[normalize-space(text())=‘Your Text Here’] Explanation: The normalize-space() function removes leading and trailing whitespace from a string and replaces sequences of whitespace characters with a single space. This XPath expression compares the normalized text of each element with the specified text
Hey Mazay,
Using Text Node Selection:
XPath: //*[text()=‘Your Text Here’] Explanation: This XPath expression selects elements whose content matches the specified text. It selects elements based on their text nodes, so it won’t match elements with the text as part of their attributes or descendants.