XPath Expressions using Functions

This lesson covers the usage of functions in writing XPath expressions.

We'll cover the following

XPath functions in Selenium

There are various functions that are supported in Selenium. Let’s discuss the most widely and commonly used ones.

Examples

The HTML structure for the following examples of different XPath functions are as follows:

<input type="radio" id="cri-sports" value="cricket-game">Cricket</input>

  • contains(): is used to identify a node/element by ensuring that it contains certain attributes values.

    General Syntax:

    //tag[contains(@attribute, 'some-value')]
    

    XPath expression for the above HTML element:

    //input[contains(@id, 'cri-sports')]
    
  • text(): helps in identifying a node/element using its text value.

    General Syntax:

    //tag[text()='text-value']
    

    XPath expression for the above HTML element:

    //input[text()='Cricket']
    
  • starts-with(): checks the starting text of an attribute value.

    General Syntax:

    //tag[starts-with(@attribute, 'some-value')]
    

    XPath expression for the above HTML element:

    //input[starts-with(@value, 'cricket')]
    
  • Combination of multiple functions: identifies or locates an element using XPath expression.

    //input[contains(text(), 'Cricket')]
    

    Or,

    //input[contains(text(), 'Cric')]
    

Let’s take a look at the example code below showing XPath functions:

Get hands-on with 1200+ tech skills courses.