is it good practice to use relative path in xpath more than once I am using Selenium Webdriver-Java to automate a web application.

Suppose the html is somewhat like below:

&lt;div id='a1'&gt;
   &lt;div&gt;
       &lt;div&gt;
          &lt;span id='s1'&gt;sometext&lt;/span&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;


To locate a element i am using xpath as below:

//div[@id='a1']//span[@id='s1']


is this xpath a good practice

or is it bad practice to use relative path(//) twice in a single xpath?
is it bad practice to use relative path(//) twice in a single xpath?


It would depend on the HTML source of the code - how many elements are there in the path between the nodes, how unique are the elements and their attributes, in general.

In this case though, it is perfectly okay - it is even better than having:

//div[@id='a1']/div/div/span[@id='s1']


because here we check more nodes on the way to span and we start to depend on the markup even more than before - this means our locator is more fragile, less resistant to a design/layout change.

In general, you should avoid using XPath locators if possible - they are the slowest and the least readable. Selenium offers much more options for locating elements:


by CSS selector:

driver.findElement(By.cssSelector("#a1 #s1"));

by ID:

WebElement parent = driver.findElement(By.id("a1"));
WebElement child = parent.findElement(By.id("s1"));



Note that we are not checking tag names here at all - it is a good idea to not use "container"-type tags like div and span inside locators.

IDs are the fastest available locators - locating an element by id internally comes down to executing getElementById() which is optimized by the modern browsers. IDs are also unique by definition (even though nothing prevents you to create two or more elements with the same ID).