A good XPATH expression, as per Chat GPT, should be
Specific
Simple
Reusable
Efficient
Readable
Awesome!
Now, what does this mean?
“You need to find this by yourself, Alex, this is as far as I can take you!”
Joking aside,
For an XPATH expression to have these attributes, it should use
specific tags (no *)
specific attributes that are created for test automation purposes (no class, type, etc)
unique and complete attribute values
It should not use
indexes
XPATH axes (sibling, child, parent, etc)
XPATH functions (contains, starts-with, etc)
logical operators
text values
It should be short with
1 search, maximum 2 acceptable
one attribute ideally
It should work in similar contexts.
For example:
1. XPATH expression for the 1st result in a results page should work for 1st, 2nd and 5th results pages
2. XPATH expression for search textbox should work if the site is used in English but also in French
Some examples follow.
The good
//button[@testid = ’username’]
//div[@testid = 'header']//input[@testid='email']
//div[@testid = 'header']/div[@testid='menu']
The bad
//button[contains(@testid,'username')]
//input[starts-with(@testid,'username')]
//span[text()='UserName']
//button[@testid = ’signup-button’]/a
//span[@class = 'form']
//input[@value="email" and contains(@class,’web’)]
(//input[contains(@testid,'result')])[2]
The ugly
//form[contains(@class,'form')]//following::div//input[@id='userpassword']
//form[contains(@class,'form')]//following::div//button/../input[@id='userpassword']
(//div[contains(@class,'custom__border')]//following-sibling::div)[1]
//button[@data-testid='signup-button']//preceding::input[@type='password']
//div[contains(@class,'custom__border')]//preceding-sibling::div
//div[@aria-labelledby='sign_up_with_google_label']//child::span
//button[@data-testid='signup-button']//parent::div//preceding-sibling::div//input[@type='password']
//div[contains(@class,'overflow-hidden')]//descendant::span
//input[@type='password']//ancestor::div//input[@id='email']
/html//div/div/div/div/div/div/div/img
What should you do if the HTML of the site does not allow creating good XPATH expressions?
First, ask the dev team to improve the HTML code by adding id attributes with static values to all important page elements.
If this is not possible, annotate each test with @Flaky so it is clear how the test will be.
Thanks for reading.
PS:
If you are interested in a full Selenium project built from A - Z, please find it here.
Thanks for this useful article. Can you add examples for "It should use" part and "It should not use" part. It ll be so helpful for a beginner like me. ❤🫡