XPath Explained Simply

XPath Explained Simply

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. //a will 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:

  • Java - WebElement ele = driver.findElement(By.xpath("//a//label[@id=’linkLabel’]"));

  • C# - IWebElement ele = driver.FindElement(By.XPath("//a//label[@id=’linkLabel’]"));

  • Python - ele = driver.find_element_by_xpath("//a//label[@id=’linkLabel’]");

Leave a reply

Your email address will not be published. Required fields are marked*

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.