Tuesday, 29 October 2013

How to check the check box in selenium web driver in java?

You can see if checkbox is checked or not using below code.

Example -

//import the required packages and classes.

import java.io.File;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;



@SuppressWarnings("unused")
public class OpenGoogle {
    
public static void main(String [] arg) 
{

//set the path of the chrome driver exe file

System.setProperty("webdriver.chrome.driver", "C:\\Selenuim\\chromedriver2.8.exe");

//create the new instance of the chrome browser
WebDriver driver =  new ChromeDriver();


try{

 //set the implicit and page load time outs  

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(50,TimeUnit.SECONDS);

//navigate to given url
driver.get("https://www.google.co.in/preferences");

//Maximize the browser window
driver.manage().window().maximize();


boolean x  = driver.findElement(By.id("myid")).isSelected();

//if check box is not selected, select it using click method.
if (x == false)
driver.findElement(By.id("myid")).click();

//This is how you can check the checkbox.

//Using same logic, you can uncheck or deselect the checkbox as displayed below.

boolean x  = driver.findElement(By.id("myid")).isSelected();

if (x == true)
driver.findElement(By.id("myid")).click();

Thread.sleep(2000);

}

catch(Exception e){
 System.out.println("Exception - > " + e.toString());
 }
 finally{
  driver.close();
  driver.quit();
 }
} //main function ends

}//class ends

What do you think on above selenium topic. Please provide your inputs and comments. Thanks

No comments:

Post a Comment

Buy Best Selenium Books