[フレーム]

Automation

Selenium WebDriver tutorial Step by Step

You are here: Home / Basic Selenium / How to write Dynamic XPath in Selenium

How to write Dynamic XPath in Selenium

by 173 Comments

[画像:Text method in Selenium XPath]

Welcome to Selenium tutorial, today we will see how to write Dynamic XPath in Selenium because we can’t go ahead without XPath and CSS so let’s discuss XPath different methods in detail. Selenium has 8 locators which include id, name, classname, XPath, CSS , linkText, partialLinkText and tag name which make our task easy to find elements.

Previously we have firebug and firepath in Firefox which helped us to find and locate XPath in a simple manner but now both are officially deprecated now we have very easy Chrome Extension called ChroPath which does the same job. I have a detailed video on this which talks about how to use ChroPath.

One more plugin to find XPath called XPath Checker but I love ChroPath

Even if you don’t want to use any plugin then still you can find XPath in chrome browser using the normal search box, for this as well I have a detailed video which talks about how to find XPath in chrome browser without any plugin .

Once you are done with XPath, I will highly recommend you to visit Dynamic CSS as well which is highly used in Cross-browser Testing as well.

Here is the Youtube video for Dynamic XPath

[フレーム]

[フレーム]

Dynamic XPath in Selenium Webdriver

Relative XPath method

Using single attribute

// tagname[@attribute-name=’value1’]
Example
// a [@href=’http://www.google.com’]
//input[@id=’name’]
//input[@name=’username’]
//img[@alt=’sometext’]

And so on.

Dynamic XPath in Selenium

Using multiple attribute

//tagname[@attribute1=’value1’][attribute2=’value2’]
//a[@id=’id1’][@name=’namevalue1’]
//img[@src=’’][@href=’’]

XPath in Selenium1

And so on.

Using contains method

Syntax
//tagname[contains(@attribute,’value1’)]
//input[contains(@id,’’)]
//input[contains(@name,’’)]
//a[contains(@href,’’)]
//img[contains(@src,’’)]
//div[contains(@id,’’)]

And so on.

Dynamic Xpath in Selenium

Using starts-with method

//tagname[starts-with(@attribute-name,’’)]
//id[starts-with(@id,’’)]
//a[starts-with(@href=’’)]
//img[starts-with(@src=’’)]
//div[starts-with(@id=’’)]
//input[starts-with(@id=’’)]
//button[starts-with(@id,’’)]
And so on.

Dynamic XPath in Selenium

Using Following node

Xpath/following::again-ur-regular-path
//input[@id=’’]/following::input[1]
//a[@href=’’]/following::a[1]
//img[@src=’’]/following::img[1]

Dynamic Xpath in Selenium

Using preceding node

Xpath/preceding::again-ur-regular-path
//input[@id=’’]/ preceding::input[1]
//a[@href=’’]/ preceding::a[1]
//img[@src=’’]/ preceding::img[1]

Dynamic Xpath in Selenium

Absolute XPath method

1-/html/head/body/div/input

Absolute-xpath

Absolute-xpath1

Text method in XPath

Syntax- tagname[text()=’text which is visible on page’]

Note- While using text() method make sure you provide the exact text else it will not match

Example //b[text()=’Admin’]

[画像:Text method in Selenium XPath]

Text method with contains

Syntax- tagname[contains(text(),’partial text which you want to search ‘)]

Example – //*[contains(text(),’Employee Distribution by Subunit’)]

Text method with Contains method in Selenium XPath

Relative and Absolute XPath method

//parent-xpath/absolute xpath
//input[@id=’section’]/div/input

Hope you are comfortable with XPath now. Please start writing XPath from your side and let me know if you are facing any issue.

For More updates Learn Automation page

For any query join Selenium group- Selenium Group

Reader Interactions

Comments

  1. Narahari says

    Detailed documentation with images. Very clear notes to note for dynamic xpath.
    Thanks a lot Mukesh ji

  2. Hitesh Chaudhari says

    Hi Mukesh,

    Firsts of all thanks for the knowledge, it really helps me out with XPath. however, want your help in one scenario.
    i am dealing with multiple sites in loop and using following xpath to located and get clicked “About us” link.

    driver.findElement(By.xpath(“//a[text()=’About us’ or text()=’About Us’ or text()=’ABOUT US’ or text()=’about us’]”)).click();

    But in one site I got three elements using this xpath. No i wanted to clicked on second one. how do I do it

    Thanks,
    Hitesh Chaudhari

    • Mukesh Otwani says

      Hi Hitesh,

      You can use above xpath with indexing like (//a[text()=’About us’ or text()=’About Us’ or text()=’ABOUT US’ or text()=’about us’])[1] OR (//a[text()=’About us’ or text()=’About Us’ or text()=’ABOUT US’ or text()=’about us’])[2]

  3. Nikhil says

    Hi Mukesh can you please tell me difference between css and xpath ? which is faster and why? among all 8

    locator ?which we should we prefer under which scenario.

    Thanks in advance

    • Mukesh Otwani says

      Hi Nikhil,

      CSS always traverse forward while xpath can traverse both
      Xpath engine is different for different browsers while CSS remains same
      Moreover, IE doesn’t has its native xpath engine due which CSS works works well on IE

  4. Anil Rautela says

    Hi Mukesh,

    I want to pass variable to my contains(text(),’ ‘) method. For example,

    String organization=excel.getOrg(“Org_Net_Name”, 1, 0);
    driver.findElement(By.xpath(//div[contains(text(),’Visible Text’)]).click(); so here I dont want “Visible Text”, I want to pass “organization” which I have stored in String variable.

    How will I do this? Please share the code.

  5. Shivang Pathak says

    Hi Mukesh,

    Can you please keep more details for ” Relative and Absolute XPath method” because most of the time testers have been facing the issue to find this time of Xpath.

    Thanks
    Shivang

    • Mukesh Otwani says

      Hi Shivangi,

      Selection of property attributes while creation of relative xpath solely depends on stability of corresponding property as there is no strict guidelines for creation of xpaths. You will learn more sophisticated way of xpath creation as long as you keep on practising it. You can use chropath extension/addon in order to verify xpath which you are creating.

  6. Jyothi says

    Dear sir
    If I want to insert data by clicking add row and the textbook box differ by index and I want to read data from Excel..

    • Mukesh Otwani says

      Hi Jyothi,

      You can all achieve these by single looping mechanism. Customize your xpath in such a way that it should accept index value with iteration number and same should be used to read data from excel too.

  7. kaustubha says

    Hi Mukesh,

    Can we do Control+f to search for something or click F3 using python3 selenium? or can we get access to all window actions or keyboard actions? If you have any solution (workable solution) then please let me know I tried my ways none of them are working.

  8. SATVEER BAJWA says

    Hi Mukesh,
    Thanks for your guidance, I have different scenario in my webpage there is one element called builder where we edit our pictures and add any text, stickers on it or so on , I was trying to get the xpath of textbox that let say textbox is layer on the picture. How can I locate that layer in selenium . I have been trying since long time but I am not getting any help . please guide me accordingly.

    • Mukesh Otwani says

      Hi Satveer,

      Now a days, market is full of different types of ui components and libraries so without looking and working on web ui of application, I can’t provide any solid solution for this. Follow what exception/ error you are getting and try to find solution for same.

  9. cyrus says

    Hi Mukesh,
    This is regarding the contains method that is used to locate element from the First Video timed at around 16:08, I guess you were writing the syntax incorrectly. I wrote the below and it found the title text:
    //input[contains(@name,’post_title’)]

  10. Satwik says

    No Mukesh my question was that in tags field in the UI that is the GUI there is also a text area so when you are writing the xpath it is showing one matching node, does that mean it is within one div tag and all the other fields like TITLE and it’s corresponding text area and TAGS and it’s corresponding text area are under independent and separate divs?

    Please share me the link to this site and Uname and password Mukesh, I could not get the link. Thanks in advance!

    • Mukesh Otwani says

      Hi Satwik,

      In application which I used, there was only one textarea, all others were input box only and that was the reason it was showing one maching node. If there were more than one textareas in UI then I could gone with other attributes too.
      textarea tag can come under div tag also, as it depends UI component design.

  11. Satwik says

    In the second video of xpath after content you are looking for textarea right? But the one next to TAGS label in the UI is also has a textarea, so why is it not being shown or is getting reflected in the following command? It should have shown two then right?

    • Mukesh Otwani says

      Hi Satwik,

      Good observation but let me explain this… There were two same words, content & Content. First one was attribute of id and next one was actual text. Both are different. And you should also remember one more thing which is, creation of dynamic xpath is always case sensitive

  12. Jeby says

    Hi Mukesh,

    I have fetched a alphanumeric character and stored In a string. It doesn’t have any white characters when it is stored in a string. However when I try to pass it through dynamic xpath like, //*[text()='” + string +”‘], the strings takes some white char in bEgiNniNg and end and it cannot find the xpath. How can I solve the issue?

  13. Anjana says

    Thank You, Mukesh,

    I did till //a[test()=’ABC’]/[1] but was not getting any matching results. I tried many times but not getting the element what I was looking for but () worked like magic.

    Thank You again.

  14. Anjana says

    Hi Mukesh,

    How can I write the XPath for the element which is n number of matching result and I want to select only the one(The first one)?

    For example, There is an n number of listings and all listings are having an edit option. How can I select the first one?

    • Mukesh Otwani says

      Hi Anjana,

      Call driver.findElements which will return you list of webelements then iterate to required one
      Or
      Use indexing in xpath iteself like you have this dynamic xpath *//a[text()=’ABC’] which matches to multiple elements now use (*//a[text()=’ABC’])[1] to get first element

  15. Ashwini says

    Hi Mukesh,
    This tutorial is really very helpful and covered all the important topics. But I need more clarification on Relative and Absolute Xpath.

  16. Jayshree Gadhave says

    I start with web elements locator but it found quite difficult to guess the xpath is correct or not without firepath. As latest version not support the firepath. can u suggest the way that I can use to enter xpath and on same screen it shows the correct match or not.

  17. Mandeep says

    HI, I have cliked on Edit button on my screen .But the Treaty Excess Id is changing everytime .
    Please find the below Html.Could you please help me in finding xpath

    edit

  18. savita says

    HI mukhesh ji
    You are god of selenium.Thanku so much.it helped me a aloot.Is there any way to find out xpath in IE browser.

  19. vinod singh says

    Hi Mukesh,
    This post is amazing and very helpful. Can I write xpath in IE or Chrome browser like we do in Firefox browser?

    • Mukesh Otwani says

      Hi Vinod,

      Yes, you can write and validate your dynamic xpath in Chrome and IE. But its not easy just like we find same using FirePath in FF.
      For Chrome, 1. Enabling Developer tool, do Cntrl+F keyboard action. After this, you can see one input bx at bottom of developer tool. In that input box, test your dynamic xpath over there.
      2. developer tool, enable console then type your dynamic xpath enclosed in $x() like this Sx(“//input[@value=’q’]”). Now press enter and matching results will come up in console itself
      For IE, you can visit this link http://westciv.com/mri/

  20. vyshak says

    Hi Mukesh,

    I just started learning selenium through ur blogs. Now i am facing issue like duplicate ID name. I want to take value from Task Owner. Can u help me???

    Status:



    Task Owners:

  21. Naira says

    Hello Mukesh. Thank for Your blog, because I’m a beginner and it really helps me.
    Could You please to write down a little about text() methods, because in the video above in some cases syntax was contains(text(), ‘something’), in the others contains(text()= ‘something’). I didn’t get.
    Thanks

  22. Lee says

    Hi Mukesh

    Let say you have a multiple ‘Browse…” on the same page. But, the id is dynamic. Everytime you log into that session. So, how would I be able to define the correct button of “Browse…”?
    The only way is by something that is calls array> How does that works?
    Example:
    ==0ドル

  23. Ravi Gavkare says

    Hello Mukesh,
    Thanks for uploading such a nice and useful selenium webdriver inforamtion.

    I have one query about dynamic xpath-
    I have following scenario :
    Click on + Add button then it will add new row in the table.
    Now here whatever new row added in the table then its hard to find xpath.

    Second thing i want to add multiple dynamic xpath and want to enter text.

    Please suggest some solution.

    • Mukesh Otwani says

      Hi Ravi,

      If you are able to locate + button using xpath then after click on button, try dynamic xpath like //button[text()=’+’]/following::tr[1] to get first row. In similar fashion, you can proceed with other rows. This is just an example to navigate. Actual xpath on your application might differs.

  24. Kevin R. Mariano says

    Hi Mukesh,

    How does this work if the ID is continuously changing?
    I’m talking specifically about Salesforce.

    You’re method worked for the first run, no doubt. But when we got the new push(release), all the id changed and script failed.

    Do you recommend any unique approach to handle dynamic changes for automating Salesforce UI with Selenium Webdriver ?

    • Mukesh Otwani says

      Hi Kevin,

      Interesting question 🙂 In this case you can take label name and then following tag. You also have to check the pattern of locator which can be changed and which can not. Based on that we need to decide which kind of xpath we will write.

  25. Aklakh Ahmad says

    Hi Mukesh,
    There is multiple card in single page having unique tag name value but the place/sequence of changing dynamically. How to capture particular card?
    Thanks

  26. Ankit Nigam says

    Hi Mukesh,

    I need to find svg class element locator. I tried multiple combination but can not go inside the svg class. Can you please help me here how to find svg class locator?

  27. Devi says

    Hi This is Devi. Your Answers are very good. Can u please help me? related to project in selenium. And actually happens in the real time project. I know manual and selenium concepts but how to implement those concepts in real time project give and explain one project.

    • sangeeta says

      Hi mukesh …
      I have a question ..
      In our comapny, they told to use Automation (selenium) for regression testing first time and don’t have senior automation testers to guide . I know selenium webdriver but…how to implement all techniques in a real time project….how to verify valid and invalid values with error messages, completely.
      I felt instead of writing the codes and spending the time with exceptions,it is better to do manual testing very fast………
      Please guide me …
      Even though I know selenium and written script, but don’t know how to use it in real time project with some techniques….
      …….Everybody will explain basic execution using,find element,XPath concept,testng,Junit…..
      but I want to know, how to use which technique in which situation
      I don’t have hands-on experience much…

      Hope you will reply….
      Thank you

  28. Ranjith Samalla says

    Hi Muskesh,

    https://www.makemytrip.com/flights
    Im trying to handle Make my trip site Flights/ Domestic tab there is no Id, name or class
    i used
    1)//*[contains(@href,)]

    2)a[starts-with(@href=”//www.makemytrip.com/flights”)]
    3) //a[@href=”//www.makemytrip.com/flights”]/following::a[1]
    these are adentifying still 3 matching nodes can u pls let me how can i adentify Flight/Domestic tab

  29. Rajani says

    Hi Mukesh ,

    Id’s are getting changed dynamically in My application , I.e We are Creating Multiple Users, while login in to the application we need to verify an Image so the image id is getting changed User to user then how can i proceed(Here we dont have any text area to use Conatins or Starts-With)

    As shown below:

    can u please suggest a solution for this

    • Sridhar says

      Hi Mukesh,

      I got empty string when i use gettext() method while printing text from dropdown in Chrome….. Can please help me to find solution for this? Please see the below code which i used…

      ArrayList al= (ArrayList) driver.findElements(By.xpath(“//ul[@id=’DDL_Icon_listbox’]/li/*[@class=’selected-value’]”));
      for(WebElement we:al)
      {
      System.out.println(we.getAttribute(“innerText”));
      }

  30. swamil says

    Hi Mukesh,

    i have been following most of your Videos on You Tube and learnautomation site,your explanations are too good.

    When can we expect tutorial on collections…like list,set,Queue .

  31. Gaurav Khurana says

    One of the best tutorial. I am not sure why i was away from it for so many days. Found it on Quora. Thanks Keep sharing the great things.

    It would be good to include CSS selector as well.
    for example
    css=a#id
    css=a.classname

  32. pooja pilkhwal says

    hi mukesh
    can you please tell me how to handle dynamic id .
    Scenario:-create one folder under one folder upload 50 files.
    every time when we upload files ,id will be change .now that time i note all file id in excel after that one -by-one file will be scheduled .so.how can handle id in code .

  33. Vaishali says

    Hi Mukesh,

    Thanks a lot for sharing of Selenium which is so informative and very helpful.

    Can you help me,

    In my application the tabs which are used are dynamically changing and have to use SkipException but, i am not able to apply it.

    Example :- Billing Manager, Claims Manager, Insurance and so on…

    sometimes “Insurance Tab” is not in use.

    Please, if you can help me, it will be a big help.

    Thank You ..waiting for your reply.

  34. Ranjith Billakanti says

    Hi Mukesh,

    Thanks for your posts, your posts are more informative, i am facing issues for one field to uniquely identify. could you please provide solution for this pls.
    details:
    Field name : Vendor
    Attributes :
    when i modfiy xpath as //input[@name=’C_BPartner_ID’] it is matching with 4 nodes
    and tried with multiple attributes using “And” operation as well.

  35. VDS Anusha says

    Thank you so much mukesh for uploading this video. It’s really awesome, after watching this video i got clearance o xpath

  36. ashok mandadi says

    Hi mukeh,
    Good afternoon,
    I am new in testing tools,i am learning manual+selenium but i can follow your site and i learn lot of things in your site,
    Is it possible to upload manual testing then can learn very fastly like doubts something like this.

  37. Neeraj Attri says

    Hi Mukesh Otwani,
    //tagname[@attribute1=’value1’][attribute2=’value2’] i think second attribute should start with @ .

  38. Ashim Paudel says

    Thanks for the awesome tutorial. I have been stuck with my selendroid automation coz I could not figure out how to combine two attributes. Saved my day….

  39. Divya says

    hey Mukesh

    very informative blog, can you please tell me how to find the xpath of last input field using last() or count() function?

    I have used following code, but it dint work

    //input[@type=’checkbox’][last()]

    regards
    Divya

  40. lalitha says

    Hi Mukesh,

    it`s really a nice session given by you and easy to understand even.
    Thanks! Keep posting nice sessions like this. presentation was so nice 🙂

  41. Soniya Vijaywargi says

    Hi Mukesh, I am new to Selenium and I must say your blog is awesome. I am refering this blog for my learning. Keep posting!!!

    Thank you so much.

  42. Arun says

    Hi Mukesh,

    I am following all your blogs on selenium and it is really helpful.
    I always get one question in interview. what is that challenging task you have done in selenium. I really don’t know what to answer. I am a beginner in selenium. Could you help me with some examples I can try out which quite challenging to be done in selenium

  43. Satheesh says

    Hi,

    Could you please help me on my problem,

    When I am writing xpath in fire bug and it matches perfectly with the node. But if i am using in eclipse i am getting a exception – NoSuch Element Expection.

    I Have used wait conditions as well.. Waiting for your reply.

    Thanks,
    Satheesh

  44. Anika Mittal says

    Sir,
    I wanted to know how to find xpath when your id is continuously changing. I mean last xpath doesn’t work any more. Element not found error is arising at every run.
    Please help. It’s urgent.

  45. sharayu says

    Hi, I am trying to locate the url for topmost ad link (first line) and click on it. The ad link comes in iframe and there is no good locator for which i can find element; as all the ids keep changing for every new search and class names have space in their name which doesnt evaluate in firepath. could you please help me in locating xpath or any other locator.

  46. Mayank says

    Hi Mukesh

    I found your website quite helpful in learning selenium xpaths.
    Thanks for sharing such a great information.

    I want to tell you that I am facing a problem while handling xpath which is dynamic.

    Basically the task I am trying to perform is :

    open snapdeal.com

    search external hard disk

    add to the cart(any hard disk)

    Now when I am trying to increase the quantity of hard disk in cart and I am not able to do that.

    The xpath of drop down list value keeps on changing.

    I also asked few experts..they were also not able find the solution.

    I request you to help me out.

    Thanks

  47. prathap says

    Thanks a lot for your great effort .it is understandable very easily.Seriously it is an ultimate blog liked it

    Thanks a lot
    Prathap

  48. Sandhya says

    Hi Mukesh,

    i faced this question interview.For Example in flipakart Application i choose one item and payed amount for that item.after that we will get one Reference no.i want to copy and paste that number in desktop note pad? how We can do?By using Auto it we can do it or any other procedure is there please let me know

    Thank you in advance

  49. bhaskar says

    i have faced this question in the interview. in an app. there are three obj. named a,b,c,.under each object there is button named ADDTOCART .and i want to press the ADDTOCART button(under object c only.not a and b).is there any way to click on button by only seeing the element.

  50. Anjali Aswani says

    Hi Mukesh

    Thanks for sharing your wide knowledge in Xpath.
    The way you have explained was very much easy for us to understand.

    Thanks

    Anjali

  51. Satyanarayan Panigrahi says

    Hi Mukesh….i am a big fan of you…

    Kindly share some post regarding how to handle a element using regular expression that changes regularly.

    • Mukesh Otwani says

      Hi Satyanayan,

      Thanks a ton for such a nice comment.

      I generally use start-with and contains method for handling dynamic element.

      Example if i have one field like username567 and when i reload page id change to username787 so in this you can use above xpath technique.

      Hope its clear 🙂

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

AltStyle によって変換されたページ (->オリジナル) /