An Introduction to XPath in Selenium WebDriver
Take a look at how you can use XPath in two different formats to identify dynamic elements on a webpage.
Join the DZone community and get the full member experience.
Join For FreeTest automation is booming in the IT industry, and it wouldn't be too far-fetched to begin calling automation itself an industry. However, we're not so far ahead that there will be a less manual intervention in the functional testing of any product. There are lots of test automation tools in the industry and the one which is leading the pack is Selenium WebDriver. It's not just because it's open source, but because of the versatility it carries. Selenium does not require an in-depth introduction as it should be familiar to every QA expert.
We identify WebElements through different locators on the web page when we are using Selenium WebDriver. Some of the locators are mentioned below:
- ID
- Name
- Class Name
- Link Text
- Tag Name
- Partial Link Text
- CSS Selector
- XPath
These eight locators are used to identify objects on any UI to perform testing operations with Selenium WebDriver. Among these, XPath is the most important one as it helps to handle dynamic elements.
Types of XPath
There are two main types of XPath that are used in Selenium:
- Absolute XPath: The XPath is designed with a single slash ("/") and it starts from the top of the DOM. If any change in position of the elements occurs, then it will lead to a failure in object identification. and example is: html/head/body/table/tbody/thead/tr/th
- Relative XPath: This type of XPath is used to handle dynamic objects efficiently. It is designed with a double slash ("//"), along with some methods to identify objects relatively. An example is: //input[@id='some_id']
How to Create a Relative XPath to Identify Dynamic Objects
There are some ways to create a relative XPath which further helps to identify frequently changing objects on web UI.
Let's see the ways to create a relative XPath.
Format: //tagname[@attribute='value']
This is the format of creating a Relative XPath. For example, let's go to my DZone profile page. I need to write a Relative XPath to identify my name. See screenshot below:
If you look at the screenshot above, you notice that I used div
as the tagname, class
as the attribute and user-name
as the value of the attribute. This creates a complete XPath that looks like this: //div[@class='user-name']
We can identify elements through the axis as well by using some methods like following, preceding, parent, following-sibling, self, contains, starts-with, and ends-with.
Opinions expressed by DZone contributors are their own.
Trending
-
Turbocharge Ab Initio ETL Pipelines: Simple Tweaks for Maximum Performance Boost
-
Front-End: Cache Strategies You Should Know
-
What Is Envoy Proxy?
-
Building a Robust Data Engineering Pipeline in the Streaming Media Industry: An Insider’s Perspective
Comments