Writing Conditional XPath In Selenium WebDriver

Hello Folks,

In this post, we will see how can we write conditional XPaths in selenium webdriver.

What is meant by Conditional XPaths?

If I say you to write xpath for the web element which has text or contains as “Selenium”, you can write is easily as below:

Has text= //*[text()=’Selenium’]

Contains text= //*[contains(text(),’Selenium’)]

But If I say you to write xpath for web element which does not contain or has text “Selenium” or locate all books whose price is greater than 300. You will find it difficult. We will going to learn how can we do that in locators itself.

We will take below html as example:

Webtable.html:

Scenario 1: Find all books except Selenium.

We always use equal to (=) operator to match exact values. We can also use “!=” operator to find if text does not match.

For above scenario , we can write xpath as below:

//table[@name=’BookTable’]//tbody[2]//tr/td[@data-column=’Book Name’ and text() != ‘Selenium’]

Scenario 2: Find all books which does not contains Java.

We use contains() method to check if text contains desired text. We can use opposite of that using not() method.

For above scenario , we can write xpath as below:

//table[@name=’BookTable’]//tbody[2]//tr/td[@data-column=’Book Name’ and not(contains(text(),’Java’))]

Scenario 3: Find all books whose in stock count is more than 10.

We can use > or >= operators to achieve this as below:

//table[@name=’BookTable’]//tbody[2]//tr/td[ @data-column=’In stock’ and text() > 10]

Scenario 4: Find all books whose in stock count is less than 10.

We can use < or <= operators to achieve this as below:

//table[@name=’BookTable’]//tbody[2]//tr/td[ @data-column=’In stock’ and text() < 10]

Scenario 5: Find all books whose in stock count is between 1 and 10.

We just need to combine Scenario 3 and Scenario 4.

//table[@name=’BookTable’]//tbody[2]//tr/td[ @data-column=’In stock’ and text() >= 1 and text() < 10]

I hope, you must have learnt something new from this post.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappySelenium

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning