In the current tutorial, we would shed light on various functions that can be used to create Xpaths when we possess only the partial knowledge about the HTML attribute associated with the web element. Thus In this tutorial we would have a look at the “Usage of contains () and starts-with () functions in Xpath”. The functions we will discuss are:

– contains()
– starts-with()

Situations where these functions should be used:

– When we do not have complete knowledge about the web elements HTML properties
– When the values of the attributes are dynamic i.e. changing
– When we would like to create a list of web elements containing same partial attribute value

Also Read

Application Under Test

Let us consider an example of “gmail.com”. We would try to find “Create an account” hyperlink using Xpath with the above mentioned functions.

2

Contains()

Contains method is used when we know about the partial attribute value or partial text associated with the web element.

Syntax:

To find the “Create an account” hyperlink, consider the following variations of contains() method.

By Text

–          //a[contains(text(),’Create’)]

–          //a[contains(text(),’an’)]

–          //a[contains(text(),’an account’)]

By Attribute

–          //a[contains(@id,’signup’)]

–          //a[contains(@id,’link-signup’)]

–          //a[contains(@id,’link)] // Take a note that two link would be highlighted, thus user would have to supply some additional attribute value in order to locate the link uniquely.

For all the above Xpaths, user would be able to find “Create an account” hyperlink successfully and the web element would be highlighted. Check out the following screenshot.

3

Starts-with()

starts-with() method is used when we know about the initial partial attribute value or initial partial text associated with the web element. User can also use this method to locate web elements those are consist of both the static(initial) and dynamic(trailing) values.

Syntax:

To find the “Create an account” hyperlink, consider the following variations of starts-with() method.

By Attribute

–          //a[starts-with(@id,’link-si’)]

–          //a[starts-with(@id,’link-sign’)]

For all the above Xpaths, user would be able to find “Create an account” hyperlink successfully and the web element would be highlighted just like previous screenshot.

I hope this tutorial would be useful to all the users who find it confusing to use various functions while creating Xpath.

Share this:

2 thoughts on “Usage of contains () and starts-with () functions in Xpath

Leave a Reply to Ronnie Cancel reply

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