Xpath helps in locating elements on the web page using XML expressions through querying XML documents. Performance wise XPath is slower in locating elements. And if there is no DOM element available with the given xpath, then NoSuchElementException is raised in that case.
Syntax: WebElement element = driver.findElement(By.xpath(<XPATH>));
There are two types of xpath
1. Native Xpath
It searches the web element from beginning of DOM. It is very simple.
Disadvantage is if there is any change in the path (like part of code is added or removed) then the Xpath has to be changed every time and also it take more time to locate the element.
2. Dynamic Xpath
It searches the web element from middle of DOM. This is relatively faster than Native Xpath.
Advantage is xpath doesn’t have to change every time unless there is a change in that particular path which is used to locate an element.
Let’s take an example by locating “side menu” in “https://demoapp1.tequality.tech/” page.
Step1: Open “https://demoapp1.tequality.tech/“ in browser
Step2: Hover your mouse to side-menu
Step3: Right click on the mouse and do inspect element
Step4: Hover the mouse on the selected element, Right click and copy full XPath
WebElement element = driver.findElement(By.xpath("/html/body/div/nav/div/div/ul"));
WebElement element = driver.findElement(By.xpath("//ul[@id="side-menu"]"));