24

An Introduction to XPath in Selenium WebDriver

 4 years ago
source link: https://www.tuicool.com/articles/r6NZfui
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Test 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 isSelenium 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:

  1. ID
  2. Name
  3. Class Name
  4. Link Text
  5. Tag Name
  6. Partial Link Text
  7. CSS Selector
  8. 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:

  1. 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
  2. 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:

nEjEreq.png!web

If you look at the screenshot above, you notice that I used div   as thetagname,  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.


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK