Xpath

     Xpath in SeleniumWebDriver



    I. Xpath là gì?

    - Xpath (XML Path) - an expression that is used to find element in the XML document. In the Selenium, it's a technique to navigate through HTML structure to locate element.

    Ex:


                                         //input[@id='email']

    <?xml version="1.0" encoding="UTF-8"?>

    <bookstore>

    <book category="cooking">
      <title lang="en">Everyday Italian</title>
      <author>Giada De Laurentiis</author>
      <year>2005</year>
      <price>30.00</price>
    </book>

    <book category="children">
      <title lang="en">Harry Potter</title>
      <author>J K. Rowling</author>
      <year>2005</year>
      <price>29.99</price>
    </book>

    <book category="web">
      <title lang="en">XQuery Kick Start</title>
      <author>James McGovern</author>
      <author>Per Bothner</author>
      <author>Kurt Cagle</author>
      <author>James Linn</author>
      <author>Vaidyanathan Nagarajan</author>
      <year>2003</year>
      <price>49.99</price>
    </book>

    <book category="web">
      <title lang="en">Learning XML</title>
      <author>Erik T. Ray</author>
      <year>2003</year>
      <price>39.95</price>
    </book>

    </bookstore>

    II. Xpath structure

    III. Xpath types

    3.1 Absolute xpath

    - Any small changes in path of the element that can make xpath failed.

    <html>
    <head>...</head>
    <body>
    ...
    <form id="loginForm">
    <input name="name" type="text" value="First Name" />
    <input name="name" type="text" value="Last Name" />
    <input name="email" type="text" value="Business Email" />
    <input name="password" type="password" />
    <input name="continue" type="submit" value="Sign Me Up" />
    </form>
    </body>
    </html>
    html/body/form/input[3]

    3.2 Relative xpath

    - Element to be searched at anywhere in HTML.
    - The element path is easy to catch up and understand.
    //form/input[3]

    IV. Priority using Xpath

    1. Unique: The value of attribute must be unique.
    2. Meaning: The value attribute of the field must have meaning.
    3. Attribute: Prioritize these tags: id/class/name.