0

I have got the following html element in my Application.

  <td height="25">
&nbsp;&nbsp;&nbsp; 
 <i>text1</i>
text2
  </td>

My Objective is to get the td element for my test script.For this i got the text inside the td tag using the getText method for the below element.

xpath = "//td/i[contains(text(),'text1')]/parent::td"

The method returned the following text(with beginning spaces)

      text1 text2

So i copied that text into the below xpath to get the td element.

xpath = "//td[contains(text(),'text1 text2')]"

However i get a NosuchElement Exception for the above element. How is this possible?

Note : I cannot use the first xpath in my script because there are several td elements like this with a common i tag text(text 1) but a different td tag text(text2, text3...)

  • 1
    Possible duplicate of [XPath: difference between dot and text()](https://stackoverflow.com/questions/38240763/xpath-difference-between-dot-and-text) – Andersson Oct 16 '18 at 13:30
  • 1
    Try `"//td[contains(normalize-space(),'text1 text2')]"` – Andersson Oct 16 '18 at 13:33
  • @andersson this worked thanks! Though i disagree on this being a duplicate -question is entirely different and the 'normalize-space' method finds mention only in the comments section. – Karthik Srivatsan Oct 16 '18 at 14:30
  • 1
    Using `normalize-space()` is a workaround for this issue. Understanding the difference between `.` and `text()` will help you avoid this issue altogether. – JeffC Oct 16 '18 at 19:40

1 Answers1

0

Selenium catches WebElement, which hold the element and all child elements text. In this case, the <td> element text is a combination of &nbsp;&nbsp;&nbsp;, text1 and text2, so when you get the text using the first expression you get text1 text2. However, there is no element in the DOM which text text1 text2, as text1 belomgs to the <i> element. Try

//i[contains(text(),'text1')]/parent::td[contains(text(),'text2')]
Guy
  • 46,488
  • 10
  • 44
  • 88