XPath Functions

When using XPaths in Selenium, there are a number of functions that can be used to speed up or improve our XPath, especially when talking about dynamic content.

Contains()

It is a method that is used in XPath expression and is used to locate the element with the partial text in the case where the text to be searched has too lengthy and the value of attribute changes dynamically on reload.

Example:

Xpath = //*[contains(@name='inputButton')]

Following

This method selects all the elements of the current node in the HTML DOM structure.

Example:

Xpath=//*[@type='password']//following::input[1]

Ancestor

This method is used to select all the ancestor elements from the current node. The ancestor can be grandparents, parents of the current node in the HTML document.

Example:

Xpath=//*[text()='Introduction']//ancestor::div

It will find all the ancestors of the current web element matches the criteria of text()= ‘Introduction’ having the div tag.

Child

This method is used in the scenarios in which we want to select the child elements of the current node in the HTML document.

Example:

Xpath=//*[@id='email']/child::div

Proceeding

This method is used to select all the nodes proceeding to the current node or the ones that come before the current node.

Example:

Xpath=//*[@type=button]//preceding::div

Following-sibling

This method is used to locate the siblings which are at the same level as the current node.

Example:

Xpath=//*[@type=button]//following-sibling::div

Parent

This method is used to locate the parent of the current node in the HTML document.

Example:

Xpath=//*[@id=['password']//parent::li

Self

This method is used to locate itself in the HTML document. Self signifies the current node only.

Example:

Xpath=//*[@id='email']//self::input

Descendant

This method is used to find the descendants of the current node in the HTML document.

Example:

Xpath=//*[@id='email']//descendant::a

Start-with

This method is used in the scenarios when we want to match the starting text of the attributes and when we need to locate the web element when the attribute changes dynamically on refreshing and reload a web page.

Example:

Xpath=//label[starts-with(@name, 'mess_avg')]