Using XPATH to search text containing  


We can use the locator xpath to identify elements having search text with   or spaces. Let us first examine the html code of a web element having trailing and leading spaces. In the below image, the text JAVA BASICS with tagname strong has spaces as reflected in the html code.

If an element has spaces in its text or in the value of any attribute, then to create an xpath for such an element we have to use the normalize-space function. It removes all the trailing and leading spaces from the string. It also removes every new tab or lines existing within the string.

Syntax

//tagname[normalize-space(@attribute/ function) = 'value']

For the web element JAVA BASICS appearing on the page, let us create an xpath// strong[text()='JAVA BASICS'] (without considering the spaces in the text). If we validate it in the Console with the expression - $x("//strong[text()='JAVA BASICS']"), we shall find there is no matching element(identified with length – 0).

Now, let us create an xpath expression using the normalize-space function. The xpath expression should be - //strong[normalize-space(text())='JAVA BASICS'].

Output

If we validate it in the Console with the expression - $x("//strong[normalizespace( text())='JAVA BASICS']"), we shall find there is a matching element(identified with length – 1).

On hovering on the result obtained, we shall find the text JAVA BASICS getting highlighted on the page.

Updated on: 08-Feb-2022

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements