0

I have a readymade code and i'm trying to write tests for it using selenium. This is how my code looks like in element tab of chrome:

<table id="xyz">
    <tbody>
        <tr>...</tr>
        "
            I am not able to retrieve this text.
        "
    </tbody>
 </table>

Doing this $x("//*[contains(text(),'I am not able to retrieve this text')]"); in console tab of chrome shows no results. I'm able to get text by this command if the text is defined in a div, span etc. (Also case sensitivity is not a problem).

In code that text is appended in tbody using jQuery('tbody').append( abc() ); and abc() function returns this text in this way pqr.html();

Now my questions is what xpath expression should i write to grab this text? And i am looking for a pure xpath expression i.e no java functions etc.

JRodDynamite
  • 12,325
  • 5
  • 43
  • 63
Shubham Gupta
  • 227
  • 2
  • 9

2 Answers2

0

contains() expects singular value as the first parameter. An HTML element may have more than one text nodes children in it, in which case, your attempted XPath will evaluates only the first text node. According to the sample HTML posted, the first text node of <tbody> which will be evaluated consists of newline and some spaces, hence your XPath didn't consider <tbody> a match and returned no result.

To avoid the problem explained above, use contains() in predicate for individual text nodes like the following :

//*[text()[contains(.,'I am not able to retrieve this text')]]

or this way if you want to return the text node itself instead of the parent element :

//*/text()[contains(.,'I am not able to retrieve this text')]
har07
  • 88,338
  • 12
  • 84
  • 137
  • It worked. But i ran into another problem. I initially didn't mentioned in the description of this questions but there are two places in the DOM where this text appears. Now when i'm trying to get the text from the desired place, it is not letting me to get that. This is the command that i'm using "//html/table[@id, 'xyz']//*/text()[contains(.,'I am not able to retrieve this text')]" and "//html/table[@id, 'xyz']/text()[contains(.,'I am not able to retrieve this text')]" – Shubham Gupta Feb 29 '16 at 16:45
  • I figured it out by myself. "/html//table[@id='xyz']//*/text()[contains(.,'I am not able to retrieve this text')]". Thanks for your answer. It saved a lot of effort of mine – Shubham Gupta Mar 01 '16 at 15:15
0

That table element is probably within a frame. To access contents within a frame you need to first switch to it. You can use the "switch to" method in selenium. Refer this answer and this one.

For the same reason it is not working in the Chrome Dev Tools console. In the console tab, there is dropdown containing a list of frames. Make sure you select the correct frame in which the specific element exist and then execute your XPath.

Community
  • 1
  • 1
JRodDynamite
  • 12,325
  • 5
  • 43
  • 63