xpath contains() text in Selenium

Contains() function in selenium

xpath is a widely used element locator in Selenium most of the testers prefer to use xpath As it is simple to use and most of the browser supports it.

There are different types of element locators in Selenium most prefer method is by ID , but if unique ideas not present then we have to switch to xpath

 contains text in selenium is used when you have to identify an element with help of text which is visible on an web page.

contains text in selenium is widely used 

 In below screenshot take an example of forgot password link if I want to identify this link using contains text I will use forgot password in the method

xpath contains text

Contains() is used with text() function

//contains(text(), "sometext")

So inside contains() method have to call text() method as a one parameter and other parameter as expected text. Xpath contains text method is widely used when you are dealing with the JS application because in JS application it become very difficult to identify an unique xpath for an element.

Below is the code to forgot password link using contains() method.

Open the images in new tab if you are not able to see

xpath contains text
//a[contains(text() ,'Forgotten account?')]

So above xpath is used to identify forgot password link on a Facebook page.

With help of the below table you will be able to select an element with different attributes using the xpath like ,ID name, tag name etc

Locator XPath Selector Equivalent
By class name "the-class"
//*[@class='the-class']"
By id "the-id"
//*[@id='the-id']"
By tag name "h1"
//h1
By name "the-name"
//*[@name='the-name']

I hope you like this blog if you like it please share it with others as well and let me know your thoughts about contains() method in xpath in the comment section below. you will also like read Selenium interview questions if you do please go to Selenium interview questions

Author: Saad Mansuri

Leave a Reply

Your e-mail address will not be published. Required fields are marked *