How to Find XPath in Selenium? Contains, Text, Axis

Table of Contents

Introduction of Xpath in Selenium


In the realm of web automation, precision is paramount. Selenium, a widely used automation framework, offers a potent tool called Xpath to precisely locate web elements for testing and interaction. Xpath in Selenium simplifies the process of identifying elements on a webpage, ensuring a robust automation script. In this comprehensive guide, we’ll delve into the depths of Xpath in Selenium, demystifying its usage, syntax, best practices, and more.

Why Xpath in Selenium Matters

Xpath in Selenium offers unparalleled benefits, making it a crucial tool in the arsenal of automation testers and developers. Its significance lies in its ability to:

  • Navigate complex DOM structures seamlessly.
  • Locate elements based on their attributes, positions, or relationships.
  • Understand changes in the web page’s structure, ensuring robust scripts.
  • Provide flexibility and precision, enhancing automation efficiency.

Types of XPath In Selenium

Absolute XPath

Absolute XPath in Selenium is a type of XPath that starts from the root element of the HTML document. It is represented by a single slash ‘/’.

However, the absolute XPaths are easy to write, but they can be fragile if the HTML structure of the page changes.

Absolute Xpath

Some of the advantages of using absolute XPath in Selenium:

  • It is easy to write.
  • It is unambiguous.
  • It can be used to locate elements that are not visible on the page.

Disadvantages of using absolute XPath in Selenium:

  • It can be fragile if the HTML structure of the page changes.
  • Longer than relative XPaths.
  • It can be more difficult to maintain.

Here are some of the ways to use absolute XPath in Selenium:

Using the tag name

You can use the tag name of the element to locate it. For example, the following XPath will locate the root element of the HTML document:

/html

Using the attribute value

You can use the attribute value of the element to locate it. For example, the following XPath will locate the <input> element with the attribute name equal to username:

/html/body/input[@name='username']

Using the text content

You can use the text content of the element to locate it. For example, the following XPath will locate the element with the text content “Sign in”:

/html/body/*[text()='Sign in']

Using a combination of methods

You can also use a combination of the methods above to locate an element. For example, the following XPath will locate the <input> element with the attribute name equal to username and the text content “Username”:

/html/body/input[@name='username' and text()='Username']

Relative XPath

Relative XPath in Selenium is a type of XPath that starts from the current node or a selected node. It is represented by a double slash ‘//‘ denoting the current node.

It is always preferred over an absolute XPath as it is not a complete path from the root element.

Relative XPath In Selenium Example

Here are some of the advantages of using relative XPath in Selenium:

  • It is shorter than absolute XPath.
  • It is less fragile.
  • It is easier to maintain.

Here are some of the ways to use relative XPath in Selenium:

Using the tag name

You can use the tag name of the element to locate it. For example, the following XPath will locate the first <input> element on the page:

//input

Using the attribute value

You can use the attribute value of the element to locate it. For example, the following XPath will locate the first <input> element with the attribute name equal to username:

//input[@name='username']

Using the text content

You can use the text content of the element to locate it. For example, the following XPath will locate the first element with the text content “Sign in“:

//*[text()='Sign in']

Using a combination of methods

You can also use a combination of the methods above to locate an element.

For example, the following XPath will locate the first <input> element with the attribute name equal to username and the text content “Username”:

//input[@name='username' and text()='Username']

How to Write Different Types of Dynamic XPath in Selenium

1. Using the id attribute of an element

If an id is present for an element, then you can use the following to write the Xpath using the id:

//*[@id='username']

2. Using the class of an element

If a class is present for an element, then you can use the following to write the Xpath:

//*[@class='column movable']

3. Using the src attribute of an element

If a src is present for an element, then you can use the following to write the Xpath. This is more relevant in the case of Images.

//img[@src='img/avatar-blank.jpg']
Xpath using src Attribute
XPath using src Attribute

4. Using the name attribute of an element

If a name is present for an element, then you can use the following to write the Xpath:

//input[@name='password']

5. Using the aria-pressed attribute of an element

If an aria-pressed is present for an element, then you can use the following to write the Xpath:

//option[@aria-pressed='true']

6. Using the text of an element

Suppose none of the attributes is present in an element and only text exists then the following is the way to identify using XPath:

//*[text()='This is header h1']

7. Using contains() method

Suppose you want to locate multiple elements using some common text or any other attribute of the attributes is present in an element and only text exists the following is the way to identify using XPath:

//*[contains(text(), 'This is sample')]

8. Using Logical OR

XPath allows you to combine multiple conditions using the “AND” and “OR” operators to create more specific and flexible element selections. Here’s how you can use them:

The “OR” operator is used when you want to select elements that satisfy at least one of the given conditions.

For example:

XPath -> //a[@class='external-link' or @href='/contact']

This XPath expression selects all <a> elements that either have the class attribute set to ‘external-link’ or the href attribute set to ‘/contact’.

Similarly, below you can see how you can locate it in the inspect tab.

OR Xpath locator in inspect
XPath Using OR

9. Using Logical AND

You can use the “AND” operator to combine two or more conditions, ensuring that all of them must be satisfied for the element to be selected.

For example, let’s say you want to select an <input> element with both a specific id and class attribute:

XPath -> //input[@id='username' and @class='input-field']

In this XPath expression, only the <input> elements that have the id attribute set to ‘username’ and the class attribute set to ‘input-field’ will be selected.

Another example:

And Xpath locator in inspect

Remember, XPath expressions are case-sensitive, so attribute names, values, and operators should match the actual HTML attributes exactly.

Additionally, consider using parentheses to ensure proper grouping if you’re combining multiple “AND” and “OR” conditions.

You May Like this: Selenium Interview Questions and Answers

10. Using Logical AND and OR Both

Suppose you have an HTML page with a list of items, and you want to select a list item (<li>) element that has either a class of “highlight” and an id of “item-1“, or a class of “special” and an id of “item-2“.

<ul>
    <li class="highlight" id="item-1">Item 1</li>
    <li class="special" id="item-2">Item 2</li>
    <li class="highlight" id="item-3">Item 3</li>
    <li class="normal" id="item-4">Item 4</li>
</ul>

The XPath locator to achieve this could be:

//li[(@class='highlight' and @id='item-1') or (@class='special' and @id='item-2')]

In this XPath expression:

  • The part @class='highlight' and @id='item-1' specifies the conditions for the first <li> element with the class “highlight” and id “item-1”.
  • The part @class='special' and @id='item-2' specifies the conditions for the second <li> element with the class “special” and iditem-2“.
  • The “OR” (or) operator combines these two conditions, allowing either of them to match for the element to be selected.

This locator will select both the first and second list item elements since they both satisfy one of the specified conditions.

Remember to adjust the attribute values and element types based on your actual HTML structure and the specific elements you want to target.

11. Using Multiple attributes

If you want to use multiple attributes for a single element:

//input[@id='user-name'][@type='text']
XPath Using Multiple Attriutes
XPath Using Multiple Attributes

12. Using Indexing

A. Using Square Bracket

Suppose there are multiple matches for //div/input[contains(@class,'form_input')] and the user wants to locate the second match.

Then anyone can use an index to locate the particular element. Below is the way to use Index in XPath:

(//div/input[contains(@class,'form_input')])[2]
XPath Using index
XPath Using Index

B. Using last() function

If we want to locate the last element if there are multiple matches found for an element. Below is the syntax you can use:

(//div/input[contains(@class,'form_input')])[last()]
XPath Using Last() Function
XPath Using last()

C. Using positions() Function

One can use the positions() functions to locate the element:

/** User can use = operator to locate first match **/
(//div/input[contains(@class,'form_input')])[position()=1]

/** User can use = operator to locate Second match **/
(//div/input[contains(@class,'form_input')])[position()=2]

/** User can use < operator to locate elements index less than 2 **/
(//div/input[contains(@class,'form_input')])[position()<2]

/** User can use != operator to locate elements apart from index 1 **/
(//div/input[contains(@class,'form_input')])[position()!=1]
Example of XPath Using position Function
XPath Using position()

Similarly, one can apply different Logical operations to locate the desired elements.

Locate Elements Using Different Axes In XPath

What are Axes methods in XPath?

In XPath, axes methods are used to navigate through the XML or HTML document structure. They provide a way to specify relationships between elements and their positions within the document.

Axes methods allow you to select features based on their parent-child relationships, sibling relationships, and more. There are several axes methods available in XPath:

Child Axis (child::)

This axis selects all child elements of the current context node. For example, if you have an element <parent> with child elements <child1> and <child2>, using the expression parent::child1 will select the <child1> element.

Descendant Axis (descendant::)

This axis selects all elements that are descendants of the current context node, regardless of their level in the hierarchy. It includes nested children, grandchildren, and so on.

Parent Axis (parent::)

This axis selects the parent element of the current context node.

Ancestor Axis (ancestor::)

This axis selects all ancestor elements of the current context node, including the parent, grandparent, and so on.

Following-sibling Axis (following-sibling::)

This axis selects all sibling elements that appear after the current context node in the document hierarchy.

Ancestor and following-siblings example
Ancestor and following-siblings example

Preceding-sibling Axis (preceding-sibling::)

This axis selects all sibling elements that appear before the current context node in the document hierarchy.

Following Axis (following::)

This axis selects all elements that appear after the current context node in the document hierarchy, regardless of their relationship.

Preceding Axis (preceding::)

This axis selects all elements that appear before the current context node in the document hierarchy, regardless of their relationship.

Self Axis (self::)

This axis selects the current context node itself.

Descendant-or-self Axis (descendant-or-self::)

This axis selects the current context node and all its descendants.

Ancestor-or-self Axis (ancestor-or-self::)

This axis selects the current context node and all its ancestors.

These axes methods allow you to precisely target elements within an XML or HTML document structure, enabling you to extract specific data or perform operations on particular elements based on their relationships in the hierarchy.

FAQs

Can relative XPath be used with CSS selectors?

Yes, relative XPath and CSS selectors can complement each other for more robust and adaptable element identification strategies.

What happens if the starting anchor of a relative XPath changes?

If the starting anchor changes, you’ll need to update your relative XPath expression accordingly to ensure accurate element identification.

Is relative XPath slower than absolute XPath?

In most cases, relative XPath is slightly faster than absolute XPath due to its focused navigation within the DOM hierarchy.

How can I handle elements with dynamic attributes using relative XPath?

You can use partial attribute values and predicates to handle elements with dynamic attributes effectively.

Can relative XPath locate elements in iframes?

Yes, relative XPath can locate elements within iframes, provided you switch to the iframe context before using the XPath expression.

Is there a performance impact when combining multiple axes?

Combining axes can increase the complexity of the expression, potentially affecting performance. However, the impact is usually minimal.

You May Like:

Leave a Comment