tags:

views:

55

answers:

3

I have played for a while writing XPath but am unable to come up with exactly what I want.

I'm trying to write XPath for link(click1 and click2 in code snippet below) based on known text(myidentity in code snippet below). Can someone take a look into and suggest possible solution?

HTML code snippet:

<div class="abc">
  <a onclick="mycontroller.goto('xx','yy'); return false;" href="#">
    <img src="images/controls/inheritance.gif"/>
  </a>
  myidentity
  <span>
    <a onclick="mycontroller.goto('xx','yy'); return false;" href="#">click1</a>
    <a onclick="mycontroller.goto('xx','yy'); return false;" href="#">click2</a>
  </span>
</div>
A: 

See Macro's answer - this form should be used.

//div[text()[contains(., "myidentity")]]/span/a[2]

The following only works with one section of text in the containing div.

You'll need to select based on the text containing your identity text.

Xpath for click1

//div[contains(text(),"myidentity")]/span/a[1]

Xpath for click2

//div[contains(text(),"myidentity")]/span/a[2]
s_hewitt
In the example provided there is more than one text element to the div tag which would cause the above to fail as the first argument to contains must be a single element
Macros
@Macros: That's correct. `//div[text()[contains(., "myidentity")]]/span/a[2]` is better.
Tomalak
+1 - have updated my answer to reflect the different predicate
Macros
great ...thank you guys this is xpaths you provided works fine
doneright
I just slightly modified xpath to click on specific link by addng anchor text //div[text()[contains(., "myidentity")]]/span/a[./text()='click[1/2]'
doneright
You should accept Macros' answer, since he has what you actually used.
s_hewitt
+2  A: 

Hard to say without seeing the rest of the HTML but the following should work:

//div[text()[contains(., "myidentity")]]/span/a
Macros
+2  A: 

You don't need to use XPath here, you could use a CSS locator. These are often faster and more compatible across different browsers.

css=div:contains(myidentity) > span a:nth-child(1) //click1
css=div:contains(myidentity) > span a:nth-child(2) //click2

Note that the > is only required to workaround a bug in the CSS locator library used by Selenium.

Dave Hunt
thank you Dave. css you provided works great
doneright