Finding the correct and appropriate xpath is very important. There are many tools and browser plug-ins to find xpath but most of theme are not appropriate. They provide an xpath which does not always work. For example:

In this page: we need the xpath for ‘View all Clinic’ text.

The firepath adons provides us an xpath:


Which is very confusing, specially when we review any code it does not make any sense that what this xpath is for.

We can easily resolve this problem and create a better xpath which will be more understandable.

For this we will use Chrome browser. Now load the page then right click and click Inspect elements.

Now from the Elements tab click show console button. It will show both the Elements and Console panel.

both element and console

Now right the xpath in the console section like bellow and press enter:

$x("//div[2]/div[contains(text(), 'View all Clinic')]")

It will show the element part at bellow and hovering the element it will highlight in the page view.

find element with xpath

In the above example we have used “//div[2]/div” because there are two elements with the same text “View all Clinic”. We need to find the second one, that’s why we have used //div[2]/div.

Here’s an example with different attributes:

$x("//strong[contains(text(), 'Patient Experience Ratings')]")
 $x("//span[contains(@class, 'arrow-link')]")

Now we will show how to maintain hierarchy:

Suppose there are various links with text ‘Edit’, but one of them is under the ‘tabs’ class.

Then we can write the xpath for that ‘edit’ element like bellow:

$x("//ul[contains(@class, 'tabs')]//a[contains(text(), 'Edit')]")

It also helps when a new ul will be added in the ‘tabs’ class because we did not consider the sequence of the ul elements, rather we have used the relative path of the ‘edit’ elements.

For starting with xpath one can type a simple a tag like:


This will show all the a tags of this page. Then narrow down by div or class or something else. By this way the output result will be narrow down and finally one can find the required xpath for the element.

Example of xpath:

Drupal Admin menu ‘Content’ link: 

$x("//li[contains(@class, 'admin-menu-toolbar-category expandable')]/a[contains(@href, '/admin/content')]")