Search This Blog

Tuesday, September 14, 2010

How to use functions in xpath in selenium

How to use functions in xpath
Automation using selenium is a great experience. It provides many way to identif an object or element on the web page.
But sometime we face the problems of idenfying the objects on a page which have same attributes. When we get more than
one element which are same in attribute and name like multiple checkboxes with same name and same id. More than one button having
same name and ids. There are no way to distingues those element. In this case we have problem to instruct selenium to identify a perticular
object on a web page.
I am giving you a simple example . In the below html source there are 6 checkboxes are there having same type and same name.
It is really tough to select third or fifth.

<input type='checkbox' name='chk'>first
<br><input type='checkbox' name='chk'>second
<br><input type='checkbox' name='chk'>third
<br><input type='checkbox' name='chk'>forth
<br><input type='checkbox' name='chk'>fifth
<br><input type='checkbox' name='chk'>sixth

Thare are some function we can use in Xpath to identify the abject in above cases.
An XPath expression can return one of four basic XPath data types:

* String
* Number
* Boolean
* Node-set

XPath Type : Functions
Node set : last(), position(), count(), id(), local-name(), namespace-uri(), name()
String : string(), concat(), starts-with(), contains(), substring-before(), substring-after(), substring(), string-length(), normalize-space(), translate()
Boolean : boolean(), not(), true(), false(), lang()
Number : number(), sum(), floor(), ceiling(), round()

I will show you how we can use some of these above functions in xpath to identify the objects.

Node Set : last()

In the above html file there are six checkboxes and all are having same attributes (same type and name)
How we can select the last checkbox based on the position. We can use last() function to indentify the last object among all similar objects.
Below code will check or uncheck the last checkbox."xpath=(//input[@type='checkbox'])[last()]");

How we can select the second last checkbox and third last checkbox. We can use last()- function to indentify the last object among all similar objects.
Below code will check or uncheck the second last checkbox and thrid last checkbox respectively."xpath=(//input[@type='submit'])[last()-1]");"xpath=(//input[@type='submit'])[last()-2]");

Node Set : position()

If you want to select any object based on their position using xpath then you can use position() function in xpath.
You want to select second checkbox and forth checkbox then use below command"xpath=(//input[@type='checkbox'])[position()=2]");"xpath=(//input[@type='checkbox'])[position()=4]");

above code will select second and forth checkbox respectively.

String : starts-with()

Many web sites create dynamic element on their web pages where Ids of the elements gets generated dynamically.
Each time id gets generated differently. So to handle this situation we use some JavaScript functions.

XPath: //button[starts-with(@id, 'continue-')]  

Sometimes an element gets identfied by a value that could be surrounded by other text, then contains function can be used.
To demonstrate, the element can be located based on the ‘suggest’ class without having
to couple it with the ‘top’ and ‘business’ classes using the following

XPath: //input[contains(@class, 'suggest')].

For rest of the function please keep reading my blogs i will be posting very soon.


  1. Hey man, thanks for the post. It helped me in writing one of my Cucumber scripts. Thanks!

  2. How would you use a number function to return all cells that have a value meeting a certain condition? For example, I want to locate all cells with a value > 5?

    I tried //tr[number(td) >5]/td but it's not returning anything.

    And a part of the DOM I'm traversing with this logic is:

    The value of '8' is greater than '5' so I'm puzzled as to why this isn't returning. Any thoughts?


  4. Again niraj ur post helped me ... Kudos to you.Keep it doing lyk this for us.
    Thanks a ton.... :)

  5. Thank you so much for posting, exactly what I was looking for.


    "I tried above X path. but it is not working.

    1. Are you sure there are more than one elements with attribute@Type=submit. This will work if there are more than one element having same attribute @type=submit


    I tried above X path to check the check box. But ending with below error.

    ERROR: Element //input[@type='checkbox'][last()-2] not found on session 6ff4de71047e441a8f2afff098e7f1c0

  8. Hi bhanu pratap,
    You have used"//input[@type='checkbox'][last()+1]");
    [last()+1] means element exist after last in that group which does not exist.
    to point out 2nd last element of that group.

  9. Hi Niraj,
    Is there a way in selenium IDE, we can automate starts_with, I mean script automatically generates "//button[starts-with(@id, 'continue-')] ", rather than button[ID='continue-234']. If selenium IDE can do this directly then user who ever is recording does not need to modify it every time. As my application web based, I need this always.


  10. If I want to use the "Starts-with" built in function do I need to download any function from this site?

    1. No its javascript funtion in-build with selenium

  11. This comment has been removed by the author.

  12. Hello, great post - thanks, but I have a problem with a complicated dyn-structure, i.e.:
    < div id="c">
    < div id="c:0:1">
    < div id="c:0:2">
    < a id="c:0:3".../>
    < a id="c:0:4".../>
    < /div>
    < div id="c:1:1">
    < div id="c:1:2">
    < a id="c:1:3"/>
    < /div>
    < /div>
    < /div>

    searching last "a" (here c:1:3) tried:

    //a[@id='c:'][last()] -found 2nd a (c:0:3)
    //div[@id='c:'][last()] -found div 0:2

    how can i find last "a" (c:1:3) or last div (c:1...)?
    PS after preview: sorry for format, how can i write here formated codes?

  13. Moderate tо ѕtгong windѕ blowing frοm thе southwest tо south
    will prevaіl οver northеrn and Central Luzon anԁ coastal ωatегs along
    thеse агеas will be moderate to rоugh.
    Offiсe goeгs and ρeoρle who are
    trаνelling often do not get timе to read news from the
    newspapеr or watсh іt
    to get gooԁ informatiοn they could subscribe for sports
    SМS alerts. It's more than just doing the right things or being involved in a good opportunity.

    Here is my web blog ... Latest Daily News

  14. The final step toward making your funny picture or video popular is to find
    the right distribution. Regardless, to locate quality photos like this
    try the following. Laughter is the finest medication, and we need to
    partake in it as typically as we are ready to do so.

    Here is my site ... lol pictures

  15. Fastidious answers in return of this query with real arguments and describing everything
    on the topic of that.

    My web page ::

  16. Small women are believed to find it more complicated to
    use fat than larger women as they have got a smaller calorie need.
    The fitness vacation - Whenever vacation is referred to, most
    of would think enjoying tropical foods, sitting beside the pool, drinking,
    and partying all night. This can be achieved by adding
    more weight, increasing the number of repetitions, or
    by adding on additional sets.

    My web page

  17. Your method of describing all in this post is actually good, every
    one be capable of without difficulty be aware of it, Thanks a lot.

    My site just click the up coming site

  18. A lot of us who are under constant pressure tend to eat too much
    and do not take good care of their bodies. Blowing off some steam with a quick round of
    solo travel fitness in the morning can make your whole day brighter.
    The decisive factor is that men would want to show themselves as hot and rock solid
    before the fashionable ladies as ever.

    My webpage - exercise and fitness tips aerobic exercise

  19. Their workout routines are even available on i - Tunes for a small fee.
    You may want to try the buddy system, as lot of people find that
    this motivates them tremendously. t have to starve just because
    you think eating is making you obese.

    Also visit my blog ::

  20. Exercise can help to avoid menopause weight gain and
    reduce other risks including osteoporosis, heart disease, and arthritis.
    We know because they have done so for millions of other people.
    If the answer is I''''''ll do whatever takes''''''''.

    My web site - Http://

  21. This piece of writing offers clear idea in favor of
    the new users of blogging, that really how to do blogging.

    My webpage :: visit this website link

  22. " The site also offers items for sale, including apparel and bags emblazoned with a drawing of a mustachioed cat; I could not find any statistics about how much merchandise the website sells, but the items for sale actually looked pretty good. This is merely a reflection of the fact that people are on the lookout for a break from the stresses of life. Many people prefer the link baiting to increasing the profit in the online marketing field.

    Here is my website -

  23. So, if you want to get these amazing and funny gifs animated images,
    then what are you waiting for. That is why
    we have dedicated this page to help you renew your spirit and perhaps have a few laughs too.
    We are offering the latest news updates about your famous celebrities.

    Here is my web-site :: funny pictures about workplace

  24. Many websites are involved in the funny picture concept and
    they include the cat playing with the plaything or
    with the trainer. These make great funny pictures, and
    can be as blatant as the example I just gave, or as simple as a spelling mistake.

    simply keep in mind few websites that may lead you to fun and smiles on face.

    Also visit my homepage: very funny pictures and quotes

  25. The new tablet would be a further extension of these concepts
    and yet another step into the future of computing for Apple.
    " Earlier today some cruise ship struck land in Alaska. I want to mention a part of the Prime Law (Twelve Visions Party) which is part of Neothink.

    My blog ... Latest Daily News

  26. After looking at a handful of the articles
    on your website, I truly appreciate your technique of blogging.
    I book marked it to my bookmark website list and will be checking back soon.
    Take a look at my website as well and tell me what you think.

    Here is my weblog; weight loss reviews

    1. Your blog is displaying : Profile not available for view.

      What's that ?

  27. selenium phpunit is giving error: invalid xpath


    please help.

  28. Is there anyone to answer ?

  29. Very often, these people give up before giving the program a
    real chance to work. You have to find a way to take the
    tips you learn and make maximum use of them. ' Being physically active can promote good mental health and help you to manage stress, anxiety and depression.

    My site -

  30. Here again you want to find or even create an angle or slant in which you can take headline news and 'incorporate' it into a
    post you are composing. It’s interesting how stars get annoyed when the paparazzi takes pictures
    of them. The singer will not be charged for her public intoxication, but
    her boyfriend was charged a $30,000 bail fee to release
    himself after he was tested positive for driving under the influence.

    Also visit my web site;

  31. Early farmers often found that hybrid strains of animals
    and plants often possessed more favourable characteristics.
    Maybe it is arrogant to want to become a hero, but I find it a noble aspiration.
    This film has many familiar faces such as John Lithgow,
    Brian Cox and Tom Felton (Draco Malfoy in the Harry Potter films) but again
    we are shown just how advanced CGI is now -especially when combined with the acting talents of Andy Serkis- and it's easy to forget that Caesar isn't

    Here is my web-site ... mouse click the following webpage

  32. Тhe writе-up offers verified useful to us.
    It’s very informative and you are certainly reallу eхpеriencеd in thiѕ fielԁ.
    Yοu get oρened my face to varying vіewѕ
    on thіs paгticular subject mаtter
    tοgetheг with іntriguing, notablе anԁ ѕolid content material.

    Also νisit my web site; buy Xanax
    Check out my website Xanax

  33. This comment has been removed by the author.

  34. Hi Niraj,

    Thanks for sharing this.
    I am facing one issue if i use the same to identify elements in Webdriver. I tried to find one element as below, but webdriver throwing error.

    driver.findElement(By.xpath("xpath=(//a[@class='potMatchMenuLink']) [position()=1]")).click();

    It would be appreciable if you can help me out.

    Thanks in advance

  35. Youг wrіte-up feаtures proѵеn beneficіаl to us.
    It’s really useful and you are obviously quіte knowledgeable in this region.
    Үou have opened our еyеs in orԁer
    to numerоus opinion of thiѕ paгticular matter along
    with іntrіquing, notable аnd ѕolid
    content material.

    Fеel free tο surf to my ωebsite ...
    Check out my webpage : phentermine

  36. Pгetty! This has bеen an inсredibly ωondeгful article.
    Thаnks for ρroviding this informatiοn.

    Look at my site 888 Poker Bonus **

  37. Thousands of thanks for providing these useful information regarding the xpath functions. Initially i was looking for long time and finding no way out there, now got a good blogs.

    Thanks buddy!
    Manikandan P

  38. Hi Niraj,
    I have ran a test using Selenium IDE 2.3.0 and copied the Junit4/Remote control script into the Eclispe Classic 4.2.2 and started running my code as 'Junit4'.I see the following error:

    Invalid Xpath 2
    The selenium command in Eclipse for Xpath is:"//input[@value='Search Equipment']");
    I tried copying the Xpath using Firebug which was:

    But I get the same error. Can you please help me with this

    1. Actually, I tried copying the page html for 'Search Equipment' to make it look better for you and fix my issue quickly but unfortunately, it's not allowing me to do that

    2. The page html code : input type="submit" data-bp3value="Search Equipment" data-bp2value="Search Equipment" data-bp1value="Search Equipment" data-bp0value="Search Equipment" data-attrlist="bp0:value,bp1:value,bp2:value,bp3:value" value="Search Equipment" class="qa-auto-keyword-submit rba-button rba-btn-lvl-1 float-right rba-attr-trigger"

  39. Please update for the remaining functions..Its realy helps good to many people like me

  40. It was very nice article and very useful for Selinium learners. we are also provide Selinium online training

  41. Thanks for the great information in your blog Selenium Training in Chennai

  42. Nice post...I look forward to reading more, and getting a more active part in the talks here, whilst picking up some knowledge as well..

    Pass Box manufacturers

  43. Thanks for sharing great information in your blog. Got to learn new things from your Blog . It was very nice blog to learn about Selenium.

  44. It was very nice blog to learn about SAP BASIS. Thanks for sharing.SAP basis

  45. Don't use index. Instead use:

  46. It was very nice blog to learn about Selenium.Thanks for sharing new things.selenium training in chennai

  47. Interest to learn Selenium Online Training by Real Time Software Testing Professional Trainer having 10+ Years of Expert.
    Selenium Training

  48. Thank you for your great information on sap basis online training in India, UK, USA, CANADA.

    Online SAP BASIS Training in USA

    Learn SAP BASIS Training Hyderabad

  49. It's amazing to know that we can handle frames easily in Selenium webdriver.
    Could you please help me to know will 'https' self certificate works? And can dynamically retrieve pass value to IFrame via parameters.

    Thanks in advance.
    Keep rocking!!
    Selenium training centers in chennai

  50. PLC scada training in noida provided by 'Dynamic Institute of Automation & Controls'. Industrial automation training in Noida deliver by industry experts with 100% placement assistance.

  51. DIAC - We are Training industries in the field of industrial automation, industrial maintenance and industrial energy conservation. This opportunity for Fresher/Experienced ENGINEERS in terms of CORE Training And Placements.Call 91-9310096831.

  52. Nice....You can also visit the ....Industrial Automation products | Tradelect Tradelect

  53. We are providing Industrial Automation Training in PLC, SCADA, HMI, DCS, Motor’s, Drives, Sensors and Industrial networking. Get details on course fees @91-931OO96830/31!! Also includes Soft skill training (Personality Development, Resume Develop, & Mock Interview Sessions). This Industrial course helps fill the huge engineering skill gap across the manufacturing sector.

  54. Industrial Automation Training | PLC Scada Training | Best Automation Training in Noida, Delhi, India

    DIAC offers exclusive PLC SCADA 6 weeks training program with live project by industry expert In Noida, DIAC is an ISO 9001:2008 company offering services as well as corporate training.For more details contact us at: 9310096830.

    plc training, automation training, industrial automation training, plc training delhi ncr, automation course noida

  55. Thanks for posting such amazing post. Well explained. Keep sharing
    Selenium Training in Delhi

  56. Really very informative and creative contents. This concept is a good way to enhance the knowledge.thanks for sharing.
    please keep it up.
    selenium training in gurgaon

  57. Welcome Engineers, Students, from a technical background. We Offer 100% placement For PLC Automation Courses. DIAC is Top PLC institute in Delhi NCR, Join our training program and become a certified in PLC training in Noida. Call @9310096831.

  58. Best PLC SCADA Training Center in Noida - DIAC provides PLC and SCADA training in Delhi. PLC SCADA Course also includes Soft skill training (Personality Development, Resume Develop, & Mock Interview Sessions). This Industrial course helps fill the huge engineering skill gap across the manufacturing sector. Call @9310096831.

  59. PLC Training | Automation Training Delhi | PLC SCADA Training Noida | DIAC- 9818293887
    We have developed our syllabus to become our trained engineers an industry ready professional. Hands on training for every participant with dedicated one PLC system and PC. Call us 91-9953489987.

  60. The information which you have provided is very good. It is very useful who is looking for selenium Online Training Hyderabad

  61. Awe! What An Blog Very Helpful and interesting Really A great center for acquiring knowledge.Very Helpful Post And Explained Very Clearly About All the things.Very Helpful. Coming To Our Self We Provide Restaurant Equipment Parts .Really Thankfull For the blogger providing such a great information.Thank you. Have a Nice Day.


  62. Whatever We Are Gathering the information from the blogs,we have to keep on updating it,Urgent Care in Chicago.By getting them into one place.Really thanks for posting.Very Thankful for the Informative Post.Really Thanks For Posting.

  63. Such a useful blog, if you want more information please visit our website.
    Selenium Training in Hyderabad

  64. Thank for sharing the information Excellent article USMLE Thanks for posting.

  65. DIAC is the best PLC SCADA AUTOMATION SERVO training Institute in Delhi with a very high level infrastructure and laboratory facility. The most attractive thing is that we provide one by one attention to candidates by faculty for PLC SCADA training at sensible fees structure which is sufficient for best PLC SCADA training in Noida to attend free demo the PLC SCADA classes. Call us: 91-9953489987.

  66. Thanks For Sharing Valuable Information, Very Useful For U Mulesoft Certification Training

  67. Thank you, You have spent good time I guess to write this kind of good articles, there is lnk for xpath, please do read it.relative xpath in Selenium webdriver

  68. This concept is a good way to enhance the knowledge.thanks for sharing. please keep it up selenium Online Training

  69. Thanks For Sharing Such an Informative Post.....


  70. Great information...
    Thanks for Sharing...
    PLC SCADA Training, PLC Training, Industrial Automation Training, Internships, Industrial Training Great opportunity, Job Oriented Training, 100% placement assistance with leading industries. Call: +91 - 8447755969(Training).

  71. DIAC offers certification courses and core job in automation technologies which includes High end practical PLC and SCADA systems, HMI, VFD , DCS, SERVO and instrumentation. Training is given to working professionals, fresh B-Tech diploma graduates and undergraduate students. Call @9953489987.

  72. Thanks for posting such a great done a great job selenium Online Training Bangalore

  73. This blog has very effective content about Big data thanks for sharing this type of information.

    Hadoop big data classes in pune

    Big Data Training in Pune

    Big data hadoop training in pune

  74. Thanks for sharing this content......


  75. Thank you for taking the time to write about this much needed subject. I felt that your remarks on this technology is helpful and were especially timely.

    Right now, DevOps is currently a popular model currently organizations all over the world moving towards to it. Your post gave a clear idea about knowing the DevOps model and its importance.

    devops course fees in chennai | devops training in chennai with placement | devops training in chennai omr | best devops training in chennai quora | devops foundation certification chennai

  76. Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information.
    Selenium Training in Gurgaon 

  77. Thanks for sharing this post.

    Want to make your own website!!!
    Contact ACIL the best web design company in Delhi.

    Interested in Graphic Designing Course!!!
    Contact ACIL for the best Graphic designing Institute in Gurgaon.

    Interested in Python training!!!
    Contact ACIL for the best Python Training Institute in Gurgaon.