Tuesday, 4 August 2015

How to check if an element exists in WebDriver selenium with java?.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Elementexists {
public static void main(String[] a) throws InterruptedException {
        // Initialize driver
        WebDriver driver = new FirefoxDriver();
        //Maximize browser window
        driver.manage().window().maximize();
        //Go to URL
        driver.get("http://www.google.com");
        //Set selenium webdriver get timeout
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

        // Write search String
driver.findElement(By.id("gbqfq")).sendKeys("WebDriver");

        // Check element exists
  if (driver.findElements(By.id("gbqfb")).size() != 0) {
            driver.findElement(By.id("gbqfb")).click();
            System.out.println("element exists");  
        }

        Thread.sleep(5000);
       
        // Browser close 
        driver.close();
    }

}

No comments:

Post a Comment