In Selenium automation, if the elements are not found by the general locators like id, class, name, etc. then XPath is used to find an element on the web page.
The basic syntax of an XPath looks like this:
The XPath has several important expressions that you definitely should know.
|Selects from the root node.
|Selects nodes in the current document that match the selection no matter where they are
|Selects the current node, it is the least used XPath expressions.
|Selects the parent of the current node.
|Allows you to select attributes.
|Allow you to match any element.
There are two types of XPath:
The absolute XPath is a direct way to find the element on a web page. But the drawbacks of the absolute XPath is that if there are any changes made in the path of the element then that XPath fails.
The absolute XPath expression of the element is shown below.
The relative Xpath starts from the middle of the HTML DOM structure. It is more compact, easy to use, and less prone to broke. It doesn't need to start from the root node, which means it can search for the element anywhere on the webpage.
The relative XPath expression of the element is shown below.
XPath expressions are created manually and also by using Inbuilt utilities. In most cases, the HTML file is quite big and complex, and writing the XPath of every element manually would be quite a difficult task.
So, it is always preferred to use some utility like a Chrome browser that has a built-in utility to inspect and generate the XPath for your elements.
Let's create XPath expression for the Create a Page link on the Facebook sign-in page by right-clicking on the link and select Inspect.
It will open the HTML DOM structure as shown below.
To get the Xpath of Create a Page link, right-click on HTML Structure and select Copy > Copy XPath.
It will copy the XPath to the clipboard and when you paste it, you will see something like this: