1

What types of Xpath expressions can I use when automating web applications?

I need to know different ways of finding elements so that if I can't use an ID I can always locate the element I need to work with.

Note: This is intended to be a canonical question about Xpath expressions.

  • 4
    What was your problem? from your own answered question, It seems that you have just posted this question for knowledge sharing. I don't know How others will react on this post..but I think this is not a good practice here... – Bharat Mane Aug 22 '17 at 10:15
  • Please refer this: stackoverflow.blog/2011/07/01/… – KavinduWije Aug 22 '17 at 10:18
  • 4
    The concept of asking a question and then answering it is fine here. These tend to be considered canonical questions to build a good knowledge base. Unfortunately, this question will need a lot of editing to make a good canonical question. I will do that next. – Kate Paulk Aug 22 '17 at 12:25
  • Nice editing @KatePaulk to avoid from closing this post. – Bharat Mane Aug 22 '17 at 13:22
  • 1
    Question should mention that XPath is locator of the last resort, when name, ID, CSS class etc cannot be used, because it is fragile and flaky. – Peter M. - stands for Monica Aug 23 '17 at 14:43
4

Xpath Types

•Xpath using contains text

//div[contains(text(),'Sign up')]

•Xpath using text

//div[ (text()='Sign up')]

•Merge Xpath (combining two Xpaths together)

Xpath=(//input[@name='email'])[2]/div/div/a

•We can use multiple attributes inside the Xpaths

//input[@id='email'][@name='email']

•We can also use logical expressions like 'AND' 'OR' in an XPath expression

//input[@name='email' and @type='Phone']

//input[@name='email' or @type='Phone']

•Xpath using following, preceding

//table[@role='presentation']/following::input 

//table[@role='presentation']/following-sibling::input

//table[@role='presentation']/ preceding::input

//table[@role='presentation']/ preceding-sibling::input
  • You can indeed write @value='Email or Phone' but it means something quite different from @value='Email' or @value = 'Phone' – Michael Kay Aug 22 '17 at 10:12
  • yes, you are correct. I'll change the attribute values. Thank you. – KavinduWije Aug 22 '17 at 10:15
  • @KavinduWije, Excellent, thanks for sharing the knowledge. – Tired Of Testing Aug 22 '17 at 14:39
1

There are a few addons for Firefox that can make your life easier when it comes to locators.

I use Mozilla addon.

screen shot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.