-1

In the following snippet

HTML Snippet

I want to get xpath of the element containing the text 'This is what I should get'. I use the xpath expression html/body/div[5]/div[3]/div/div/div/div[2]/div/table/tbody/tr[2]/td/span, but I am getting the element with text 'This is what I am getting'. Please help me to modify element locator to get desired text

stackoverflow
  • 2,134
  • 3
  • 19
  • 35

2 Answers2

1

There must be a better XPath expression than that verbose one, but without more information I can only suggest based on the existing XPath. So, the desired text node can be identified either as text node that follows the previously selected span element :

..../table/tbody/tr[2]/td/span/following-sibling::text()[1]

or as direct child text node from the parent td element :

..../table/tbody/tr[2]/td/text()[normalize-space()]
har07
  • 88,338
  • 12
  • 84
  • 137
  • When I am using above xpath to automate some test scenario using Selenium and Java, I am getting exception org.openqa.selenium.InvalidSelectorException. The locator is: [object Text]. It should be an element @vxsx – stackoverflow May 19 '16 at 06:37
  • 1
    @curious alright, there is no clean XPath solution in Selenium since it doesn't support returning other than element node. You'll need to return the `` element, then do some string manipulation afterwards : http://stackoverflow.com/questions/36018524/selenium-get-a-text-node-using-xpath-and-use-it-as-a-string-in-java – har07 May 19 '16 at 06:56
0

If you want to get the text node, the xpath would be:

html/body/div[5]/div[3]/div/div/div/div[2]/div/table/tbody/tr[2]/td/text()[2]

Although xPath expression should probably less verbose.

vxsx
  • 448
  • 5
  • 12