Tricks every automation tester must follow with XPath!

Absolute vs. Relative XPath

Use Relative XPath expressions instead of Absolute ones as it is more resilient to changes in the DOM.

Using the contains function

Instead of using the full string in XPath, use the contains function to look for a substring. For example, //div[contains(@class, 'menu')].


Use wildcards like * and @* in XPath to select any element or attribute, respectively. For example, //* will select all elements on the page.

Using not in XPath

Use the not keyword to exclude elements from your XPath expression. For example, //div[not(@class='menu')] will select all divs that don't have the menu class.

Selecting by text content

Use the text() function to select elements based on their text content. For example, //h2[text()='Contact Us'] will select the h2 element with the text Contact Us.

Selecting parent and child elements

Use the ../ and ./ syntax to select parent and child elements, respectively. For example, //ul/li/a[../@class='menu'] will select all a elements that are children of li elements that are siblings of a ul element with the menu class.

Swipe up