ssc-seifert
ssc-seifert

Reputation: 115

XPath expression for element based on containing text

I'm running out of ideas. I have identified for my Selenium test an div based on its text ("security administrator ") contained. Unfortunately, the div contains two other divs. See the example.

<div class="rich-stglpanel-marker">
    <div class="rich-stglpnl-marker" id="j_id194:j_id198:2:j_id199_switch_on" style="display: none"></div>
    <div class="rich-stglpnl-marker" id="j_id194:j_id198:2:j_id199_switch_off"></div>
    security administrator 
</div>
<div class="rich-stglpanel-marker">
    <div class="rich-stglpnl-marker" id="j_id194:j_id198:2:j_id199_switch_on" style="display: none"></div>
    <div class="rich-stglpnl-marker" id="j_id194:j_id198:2:j_id199_switch_off"></div>
    technical administrator 
</div>
... and so on

I tried that expressions:

//div[text()='security administrator']
//div[text()='security administrator ']
//div[text()='security administrator&nbsp;']
//div[text()='security administrator${nbsp}'] (this is a special hack from selenium)

Nothing works. Any ideas?

Thanks in advance.

Upvotes: 2

Views: 13286

Answers (3)

niharika_neo
niharika_neo

Reputation: 8531

Can you try with this :

//div[contains(.,'security administrator')]
System.out.println(driver.findElementByXPath("//div[contains(.,'security adm')]").getText()) 

gave me security administrator

Upvotes: 5

JWiley
JWiley

Reputation: 3219

Try this: //div[@class='rich-stglpanel-marker' and text()!='']

EDIT

Finally got it!

Use this: //div[@class='rich-stglpanel-marker' and normalize-space(div[last()]/following-sibling::text())='security administrator']

I believe that in this situation, the text "security administrator" is counted as a node, and not as the sole text value of the first div node, which is why //div/text() will give you multiple return lines followed by the text you're searching for, and also why you cannot apply something like normalize-space(),translate(), or even contains() to div/text() and receive results. But, since the text node doesn't have a name, that makes it a funky XPath to figure out, so navigating to the closest possible sibling node was the only option I could think of.

Upvotes: 0

Santoshsarma
Santoshsarma

Reputation: 5667

try this

//div[@class='rich-stglpanel-marker']

Upvotes: 0

Related Questions