Basic XPath Syntax



I hope you got an Introduction to XPath in our earlier tutorial. In this tutorial, let us start exploring some of the basic XPath syntax which shall help you in your Test Automation activity.

XML Image



Sample HTML

Let us take a sample HTML which we will use to demonstrate in the subsequent examples.

<html>

<head>
    <title>Page Title</title>
</head>

<body>
    <p>
        This is a sample paragraph
    </p>
    <p>
        This is a list
    </p>
    <ul>
        <li class=”item”>List item 1</li>
        <li class=”item”>List item 2</li>
    </ul>
</body>

</html>
 


Basic Syntax

Let us explore some of the basic syntax used in XPaths

1. nodename

The node name selects all the nodes with the specified name. This is basically the XML tag name.
E.g.
head, div, p, etc.



2. /

This single forward slash syntax selects the element(s) starting from the root node.
E.g. The full path for the Title tag from the sample HTML will be:
/html/head/title



3. //

This double forward slash syntax selects the nodes matching the selection from anywhere in the document. This syntax is often used for relative xpaths.
E.g. the xpath for the list in the above sample HTML will be:
//ul
The relative path for the title in the above sample HTML will be:
//title



4. .

The dot syntax selects the current node.
E.g. If you are at the 'title' node, you can specify it as:
//title/.
Though, you may not need this often at it is not you can also directly access it without using the dot. E.g.
//title



5. ..

The double dot syntax selects the parent node of the current node.
E.g. if you have the title tag and want to access its parent tag (i.e. the head tag), then you can access it as:
//title/..



6. @

The @ syntax selects the attribute present within the given node.
E.g. if you want to access the list items having the class attribute as “item”, then you can refer it as:
//li[@class='item']

You can use single or double quotes as per your preference and need (for e.g. in case you are already using double quote to surround the xpath string in your Java/Javascript/Python code, then you may be required to use single quote, or vice versa.



I hope this tutorial gave you a good grasp of the basic XPath syntax.

Next Chapter Advanced XPath Concepts

Follow Me on Social Media

Advertisement
FREE Sales CRM Software

Fully customizable CRM Software for Freelancers and Small Businesses

Signup for Free

Sign up for DigitalOcean Cloud

Get FREE $200 credits, deploy your hobby projects for Free

DigitalOcean Referral Badge
Sign up for Hostinger Cloud or VPS plans and get upto 20% Discount