Pages

Search This Blog

Loading...

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.

<html>
<body>
<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
</body>
</html>


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.

selenium.click("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.

selenium.click("xpath=(//input[@type='submit'])[last()-1]");
selenium.click("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

selenium.click("xpath=(//input[@type='checkbox'])[position()=2]");
selenium.click("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.

46 comments:

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

    ReplyDelete
  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:

    http://screencast.com/t/xjfzRNopDq

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

    ReplyDelete
  3. THANKS FOR SHARING THE VALUABLE INFORMATION

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

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

    ReplyDelete
  6. selenium.click("xpath=(//input[@type='submit'])[last()-1]");

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

    ReplyDelete
    Replies
    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

      Delete
  7. selenium.click("//input[@type='checkbox'][last()+1]");

    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

    ReplyDelete
  8. Hi bhanu pratap,
    You have used selenium.click("//input[@type='checkbox'][last()+1]");
    [last()+1] means element exist after last in that group which does not exist.
    use

    selenium.click("//input[@type='checkbox'][last()-1]");
    to point out 2nd last element of that group.

    ReplyDelete
  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.

    Thanks,
    Suman

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

    ReplyDelete
    Replies
    1. No its javascript funtion in-build with selenium

      Delete
  11. This comment has been removed by the author.

    ReplyDelete
  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?

    ReplyDelete
  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

    ReplyDelete
  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

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

    My web page :: http://mymed2.sophia.inria.fr/wiki/Tips_And_Methods_For_The_Grocery_Store_When_You_Are_Finding_Healthy

    ReplyDelete
  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 http://www.24-7press.com/

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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 :: http://worddrum.ahaaas.com/wp/groups/deciding-upon-clear-cut-programs-for-fitness-tips/

    ReplyDelete
  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://security.deg.cz/ValentinH

    ReplyDelete
  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

    ReplyDelete
  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 - http://guysmovies.com/blogs/entry/Laughter-Is-Greatest-Medicine-Humorous

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

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

      What's that ?

      Delete
  27. selenium phpunit is giving error: invalid xpath

    $session->click("xpath=(//html/body/table/tbody/tr[4]/td[3]/table/tbody/tr[7]/td[1]");

    please help.
    Regards

    ReplyDelete
  28. Is there anyone to answer ?

    ReplyDelete
  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 - http://waterleaf.eu/

    ReplyDelete
  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; www.kiazzakiazza.com

    ReplyDelete
  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
    real.

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

    ReplyDelete
  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

    ReplyDelete
  33. This comment has been removed by the author.

    ReplyDelete
  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
    Ajith

    ReplyDelete
  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 ...
    http://132.252.182.11
    Check out my webpage : phentermine

    ReplyDelete
  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 **

    ReplyDelete
  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

    ReplyDelete
  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:

    selenium.click("//input[@value='Search Equipment']");
    I tried copying the Xpath using Firebug which was:

    /html/body/section[2]/section/div/div/div/form/div[2]/div[2]/div/span/input
    But I get the same error. Can you please help me with this

    ReplyDelete
    Replies
    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

      Delete
    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"

      Delete