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

7 thoughts on “Writing Conditional XPath In Selenium WebDriver

  1. I Almost read all your blog posts. You write all your post in simplified manner that can be easily understandable by any novice.
    I have a question : I usually forgets the syntax while writing these xpath /css and have to open some reference link. is there any better way to memorize them?

    1. Practice. Don’t use any tool to find locators. I have never used any tool yet and now i can find locators quicker.

Leave a Reply