Formed as an expression that allows the driver to navigate from the start of the document to a desired element. Looks vaguely similar to a file path when used.
How to create an XPath (simple explanation):
- Start by writing “//”. This tells the machine to start from the root element
Provide an initial element type to match. E.g.
//awill look for the first anchor tag from the root element.
Include attribute definitions using “@attribute=’something’”. E.g.
//a[@id=’wikipediaLink’]will look for the first anchor tag from the root element with an id equal to “wikipediaLink”.
This can also include more advanced search options like “contains”. E.g.
//a[contains(@id,’Link’)]will look for the first anchor tag where the id contains the partial text “Link”.
Add extra elements to look for children of initial element. E.g.
//a//label[@id=’linkLabel’]will search for the child of the first found anchor tag which has an id equal to “linkLabel” and the type “label”.
Looks like this when used in some of the more popular languages with Selenium WebDriver:
WebElement ele = driver.findElement(By.xpath("//a//label[@id=’linkLabel’]"));
IWebElement ele = driver.FindElement(By.XPath("//a//label[@id=’linkLabel’]"));
ele = driver.find_element_by_xpath("//a//label[@id=’linkLabel’]");