Skip to content
Advertisement

How to use if else condition for searching element using WebDriver in Selenium?

  1. I used else if concept
  2. I have not used try catch finally concept webdriver element finding using elseif loop

how I want it to work :

  1. First it will check for “if” condition that is [if(driver.findElement(By.xpath("username")).isDisplayed())] and if it is not found it will not print any statement.
  2. because “if” condition is not seen it will go to “elseif” condition that is [else if(driver.findElement(By.id("username")).isDisplayed())] and as “else if” statement is true, it will print and do what ever is there in loop..
    let me know on above statemnts does my below code works or not…

.

public void mytrip()throws Exception{   
    driver.get("http://yahoomail.com/");   
    if(driver.findElement(By.xpath("username")).isDisplayed()){     
        driver.findElement(By.xpath("username")).click();   
        System.out.println("clicked"); 
    } else if(driver.findElement(By.id("username")).isDisplayed()){ 
        driver.findElement(By.id("username")).click(); 
        System.out.println("clicked in else if");   
    }    
}  

problem: it is checking for if condition and as element is not found in that condition it is coming out of loop not going to elseif…

according to below concept my above code should work i feel.. if not then please let me know how to work with that..

 class IfElseDemo {
     public static void main(String[] args) {
         int testscore = 76;
         char grade;
         if (testscore > 90) {
             grade = 'A';
         } else if (testscore < 80) {
             grade = 'B';
         } else if (testscore > 60) {
             grade = 'C';
         }
         System.out.println("Grade = " + grade);
     }
 }

The output from the program is: Grade = B

Advertisement

Answer

Of course it gets out of the loop. driver.findElement throws NoSuchElementException if it cannot find the element. Your xpath is not good so it will not find the element resulting in your exception.

Boolean isPresent = driver.findElements(By.yourLocator).size()<0

try something like that to check for elements.

4 People found this is helpful
Advertisement