Sunday 7 October 2012

How to create a xpath in selenium


Xpath is language using we can get the element of the xml.

So probably you are thinking about how to create xpath using xpath language.

My point of view you should remember below mentioned point whenever you are creating xpath.

1) Always create short xpath.

2) Don’t use dynamic data(Like className,id.. etc) in xpath.

3) If you are feeling that your browser text(like button name ,link text,textbox text etc) are not changing frequently then you should use text only.

Like xpaths for link:-

//*[text()='SignIn']

//*[contains(text(),'Home')]

//*[starts-with(text(),"in your mind)]

for button:-

//*[@value='Login'] or //*[@*='Login']

etc

3) If same page having more than one xpath then use postion or create xpath depending upon the other text/control.

Like:-

//*[@*='Post'][position()=1]

if you want to access last button

//*[@*='Post'][position()=last()]

if all the button/links are getting displayed whenever you are using position=1 then use following xpath and mention postion according your requirment.

(//*[@*='Post'])[position()=3]

create xpath depending upon the other text/control:

//*[text()='Agent Page']/parent::*/parent::*/descendant::*[@*='Post']

for more details about the above mentioned functions refer following link http://www.w3.org/TR/xpath20/.

4) After creating xpath,verify same using xpath checker/firebug/xpather plugin.These are firefox plugin.

if above mentioned plugins are displaying same control as your browser.then your xpath is correct :-)

2 comments:

  1. Short and sweet,could you add some more example.

    ReplyDelete
  2. @Rajesh:what kind of example you want?,xpath language have lot of functions and you can use same for according your requirment.
    refer above mentioned link for xpath functions.

    ReplyDelete