I want to know what xpath text equals to?

689    Asked by alexGONZALEZ in QA Testing , Asked on Apr 27, 2022

In the Flipkart page, I searched for Apple ipads and clicked on the first search result. Here, I wanted to click on 'BUY NOW'.

I used the following xpath and it worked:

//button[text()='BUY NOW'] Then I used the xpath with 'contains' but it didn't work: //button[contains(text(),'BUY NOW')]

Also this: //button[contains(text(),'BUY')]

But none worked. I was really surprised as to why 'contains' is not identifying the elements. I found the same behavior with the 'Add to Cart' button as well.

Then I tried to identify another element - 'Wi-Fi+4G' with contains and it worked:

//a[contains(text(),'Wi-Fi+4G')]

//a[text()='Wi-Fi+4G']

Both the above xpath worked for me.

So, can you please explain why 'contains' is not working here?

Regarding your question - What xpath text equals, let me share my findings. First of all //button[contains(text(),'BUY NOW')] doesn't really look up the element in Chrome dev tools. But //button[contains(.,'BUY NOW')] does the trick.


If to copy paste form to this site and try to apply this xpath, it will show up the following error Unable to perform XPath operation. A sequence of more than one item is not allowed as the first argument of contains() ("", "BUY NOW")

  So let's check what text() function returns for the element, having noticed that //button[contains(.,'BUY NOW')] works, lets try to process the following: //button[contains(.,'BUY NOW')]/text(). It turns out that text() returns two text elements which is not the correct input for contains() function.

Unlike this button, [Wi-Fi+4G] does not have such the property (text() function will return the only single element for that). This is why contains works perfectly for that button.

Summing up (mostly from this discussion on SO):

text() function returns all the text nodes under the specified element. Comment tag breaks inner text into several nodes
There is a function that ignores the node structure but just converts inner text nodes into a single string, It is called string()
You can omit using string() function when use contains() but just use contains(., 'your text') since . is automatically taken as string(.)

Your Answer

Interviews

Parent Categories