How to use CSS selector to identifying web elements in Selenium Webdriver using java

CSS selector:

When there is no an option to choose web element using selector like as ID or Name etc, Selenium Webdriver prefer to use CSS locators as the best alternative to choose web element. CSS Selector is combination of an element selector and a selector value which identifies the web element within a web page. Selector Pattern is made using HTML tags, attributes and their values. CSS locators is Advantage, faster and simpler than Xpath.
Some important terms for CSS selectors
HTML tag - It is tag. HTML tags are the hidden keywords within a web page that help to define how the browser must format and display the content. In Selenium Webdriver it help to access web element which we want.
Attribute – An attribute defines a property for an web element, consists of an attribute/value pair, and appears within the opening tag. It is the attribute we want to use to create CSS Selector.
Value of attribute – It is the value of an attribute which is being access
# – The hash(#) character is used to indicate ID attribute. It is mandatory to use hash sign for ID attribute in CSS Selector.
Value of ID attribute – It is the value of an ID attribute which want to access.

. – The dot(.) character is used to introduce Class attribute in CSS locator. It is mandatory to use dot sign before class name if Class attribute is being used to create CSS Selector.
Value of ID attribute – It is the value of an ID attribute which want to access
^ – The hat(^) sign is used to match a string using prefix.
$ – The dollar($) symbol is used to match a string using suffix.
* –The symbol of asterisk(*) to match a string using sub string.
: – The dot(.) sign is used to match a string using contains method.

CSS Selector: ID
 <input id="email" type="email" tabindex="1" name="email">  
 <div id="rsi_card" class="card signin-card">  
Syntax : HTML tag_#_Value of ID attribute or HTML tag[Value of ID attribute]
Example :
WebElement idcssselector = driver.findElement(By.cssSelector("input#id=email"));
WebElement idcssselector = driver.findElement(By.cssSelector("input[id=email]"));
WebElement idcssselector = driver.findElement(By.cssSelector("div#id=rsi_card"));
WebElement idcssselector = driver.findElement(By.cssSelector("div[id=rsi_card]"));

CSS Selector: Class
 <input type="checkbox" class="uiInput" >  
 // For multiple classes  
 <input class="submit ipt second-ipt flex-table-ipt js-submit" type="email">  
Syntax : HTML tag_._Value of Class attribute
Example :
WebElement classcssselector = driver.findElement(By.cssSelector("input.uiInput"));
// For multiple classes
WebElement classcssselector1 = driver.findElement(By.cssSelector(".second-ipt"));
WebElement classcssselector2 = driver.findElement(By.cssSelector("ipt.second-ipt"));
WebElement classcssselector3 = driver.findElement(By.cssSelector("submit.second-ipt"));

CSS Selector: Attribute
 <input type="password" id="pass" name="pass">  
Syntax : HTML tag_[attribute=Value of attribute]
Example :
WebElement classcssselector = driver.findElement(By.cssSelector("input[name=pass][type=password]"));

CSS Selector: ID/Class and attribute
Syntax : HTML tag_. Or #_value of Class or ID attribute_[attribute=Value of attribute]
Example :

CSS Selector: Sub-string
Match a prefix
Syntax : HTML tag_[attribute^=prefix of the string]
Example :

Match a suffix
Syntax : HTML tag_[attribute$=suffix of the string]
Example :

Match a sub string
Syntax : HTML tag_[attribute*=sub string]
Example :


CSS Selector: Inner text
Syntax : HTML tag_:_contains_(text)
Example :

Demo Source Code

How to operate hidden or invisible web elements in Selenium Webdriver using Java

Sometime We need to handle invisible or hidden web elements but Selenium WebDriver will only interact with visible elements, therefore the text of an invisible element will always be returned as an empty string. In some cases We need to operate like as click, get text, send value etc hidden web elements. The follow attribute use to hide web element.

style="Display:none;"

 <div class="owl-prev" style="display: none;">prev</div>  

style="Display:block;"

 <div data-easeout="bounceOutLeft" data-easein="bounceInRight" data-stop="7800" data-start="300" data-height="26" data-width="184" data-y="155" data-x="183" class="md-object md-layer-1-0-0 bounceInRight" style="width: 9.58333%; height: 5.97701%; top: 35.6322%; left: 9.53125%; display: block;">DO YOU NEED AN</div>  

style="visibility:hidden;"

 <div style="position: absolute; width: 9999px; visibility: hidden; display: none; max-width: none;"></div>  

type="hidden"

 <input type="hidden" value="form-w1cPBpyG9r-0a26cL3dRYB5fM-V6O_18Ojgef4qOoXo" name="form_build_id">  

Demo Source Code

 import java.util.List;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Hiddenwebelements {  
   public static void main(String[] args) throws InterruptedException {  
     // create objects and variables instantiation     
     WebDriver driver = new FirefoxDriver();  
     // maximize the browser window      
     driver.manage().window().maximize();  
     // launch the firefox browser and open the application url   
     driver.get("http://www.yahoo.com/");  
     //Set timeout     
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     //Get all display block invisible webelement and store in List variable name is number_of_displa_block   
     List<WebElement> number_of_displa_block = driver.findElements(By.cssSelector("div[style*='block']"));  
     //Print total size display block webelements   
     System.out.println("Display Block =: " + number_of_displa_block.size());  
     System.out.println("========================================================");  
     for (int i = 0; i < number_of_displa_block.size(); i++) {  
       // Print all display block Webelements text   
       if (!(number_of_displa_block.get(i).getText().trim().isEmpty())) {  
         System.out.println("Displa Block Element = " + i + " " + number_of_displa_block.get(i).getAttribute("style").trim() + " " + number_of_displa_block.get(i).getText().trim());  
       } else {  
         System.out.println("Displa Block Element = " + i + " " + number_of_displa_block.get(i).getAttribute("style").trim());  
       }  
     }  
     //Get all display hidden webelemnt and store in List variable name is number_of_visibility_hidden   
     List<WebElement> number_of_visibility_hidden = driver.findElements(By.cssSelector("div[style*='hidden']"));  
     //Print total size visibility hidden webelements    
     System.out.println("\n\nvisibility: hidden = " + number_of_visibility_hidden.size());  
     System.out.println("========================================================");  
     for (int i = 0; i < number_of_visibility_hidden.size(); i++) {  
       // Print all hidden Web elements text    
       if (!(number_of_visibility_hidden.get(i).getText().trim().isEmpty())) {  
         System.out.println("visibility: hidden Element = " + i + " " + number_of_visibility_hidden.get(i).getAttribute("style").trim() + " " + number_of_visibility_hidden.get(i).getText().trim());  
       } else {  
         System.out.println("visibility: hidden Element = " + i + " " + number_of_visibility_hidden.get(i).getAttribute("style").trim());  
       }  
     }  
     //Get all display none webelemnt and store in List variable name is number_of_display_none   
     List<WebElement> number_of_display_none = driver.findElements(By.cssSelector("div[style*='none']"));  
     //Print total size display none webelements    
     System.out.println("\n\ndisplay: none = " + number_of_display_none.size());  
     System.out.println("========================================================");  
     for (int i = 0; i < number_of_display_none.size(); i++) {  
       // Print all display none Webelements text   
       if (!(number_of_display_none.get(i).getText().trim().isEmpty())) {  
         System.out.println("display: none Element = " + i + " " + number_of_display_none.get(i).getAttribute("style").trim() + " " + number_of_display_none.get(i).getText().trim());  
       } else {  
         System.out.println("display: none Element = " + i + " " + number_of_display_none.get(i).getAttribute("style").trim());  
       }  
     }  
     //Get input tag and store in List variable name is number_of_hidden_input_Elements   
     List<WebElement> number_of_hidden_input_Elements = driver.findElements(By.tagName("input"));  
     //Print total size input hidden webelements   
     System.out.println("\n\nInput Hidden Element =: " + number_of_hidden_input_Elements.size());  
     System.out.println("========================================================");  
     for (int i = 0; i < number_of_hidden_input_Elements.size(); i++) {  
       // Print all hidden input webelements value   
       if (number_of_hidden_input_Elements.get(i).getAttribute("type").trim().equalsIgnoreCase("hidden")) {  
         //Check empty text   
         if (!(number_of_hidden_input_Elements.get(i).getAttribute("value").trim().isEmpty())) {  
           //Print hidden Element texts   
           System.out.println("Input Hidden Element = " + i + " " + number_of_hidden_input_Elements.get(i).getAttribute("value").trim());  
         }  
       }  
     }  
     // quit Firefox browser   
     driver.quit();  
   }  
 }  

Clicking an invisible or hidden Element
 List<WebElement> number_of_display_none = driver.findElements(By.cssSelector("div[style*='none']"));  
 JavascriptExecutor executor = JavascriptExecutor)driver;  
 executor.executeScript("arguments[0].click();", number_of_display_none.get(position).getText());  
OR
 WebElement invisibleelement= driver.findElement(ElementLocator);  
 JavascriptExecutor executor = JavascriptExecutor)driver;  
 executor.executeScript("arguments[0].click();", invisibleelement);  

How to get hidden webelements text in Selenium Webdriver using Java


 import java.util.List;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class HiddenElementstext {  
   public static void main(String[] args) throws InterruptedException {  
     // create objects and variables instantiation      
     WebDriver driver = new FirefoxDriver();  
     // maximize the browser window       
     driver.manage().window().maximize();  
     // launch the firefox browser and open the application url  
     driver.get("www.yahoo.com");  
     //Set timeout      
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     //Get input tag and store in List variable name is number_of_hiddenElements  
     List<WebElement> number_of_hiddenElements = driver.findElements(By.tagName("input"));  
     //Print total number of Input tag   
     System.out.println(number_of_hiddenElements.size());  
     for (int i = 0; i < number_of_hiddenElements.size(); i++) {  
       // Print all hidden elements text  
       if (number_of_hiddenElements.get(i).getAttribute("type").trim().equalsIgnoreCase("hidden")) {  
         //Check empty text  
         if (!(number_of_hiddenElements.get(i).getAttribute("value").trim().isEmpty())) {  
           //Print hidden Element texts  
           System.out.println("Hidden Element text = " + i + " " + number_of_hiddenElements.get(i).getAttribute("value").trim());  
         }  
       }  
     }  
     // quit Firefox browser  
     driver.quit();  
   }  
 }  

How to handle Checkbox and Radio button in Selenium Webdriver using Java.

Checkbox and Radio button operations is very simple to perform like as click operation. Checkbox is always recommended to check if that is already in selected mode or deselected. Because, if it is already selected and when you click on the same element it will get deselected. We will look into different ways to perform select and de-select operations on checkboxes. Radio Button is selected by default or anything.


Page HTML Code

 <html>  
 <head>  
 <title>Checkbox and radio button test page</title>  
 </head>  
 <body>  
 <form name="myform" action="" method="POST">  
 <div align="center"><br>  
 <input type="checkbox" name="option1" value="Bike">Bike  
 <input type="checkbox" name="option2" value="Car">Car   
 <input type="checkbox" name="option3" value="Plane" checked>Plane  
 <input type="checkbox" name="option4" value="Truck">Truck   
 <input type="checkbox" name="option5" value="Milk">Milk  
 <input type="checkbox" name="option6" value="Butter">Butter  
 <input type="checkbox" name="option7" value="Cheese">Cheese  
 <br>  
 <input type="radio" name="group2" value="Water"> Water  
 <input type="radio" name="group2" value="Beer"> Beer  
 <input type="radio" name="group2" value="Wine" checked> Wine  
 </div>  
 </form>  
 </body>  
 </html>  


Demo Source Code

 
 import java.util.List;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 
 public class CheckboxandRadiobuttonhandler {  
   public static void main(String[] args) throws InterruptedException {  
     // create objects and variables instantiation      
     WebDriver driver = new FirefoxDriver();  
     // maximize the browser window       
     driver.manage().window().maximize();  
     // launch the firefox browser and open the page  
     driver.get("file:///C:/Users/Hiro%20Mia/Desktop/Blog%20content/checkbox.html");  
     //Set timeout      
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     //Get the count of all available check boxes   
     List<WebElement> number_of_checkbox = driver.findElements(By.tagName("input"));  

     //Select all checkbox and Radio if selectable  
     for (int i = 0; i < number_of_checkbox.size(); i++) {  
       //Checking Checkbox  
       if (number_of_checkbox.get(i).getAttribute("type").trim().equalsIgnoreCase("checkbox")) {  
         //Print the Check box count with value  
         System.out.println("CheckBox = " + i + " " + number_of_checkbox.get(i).getAttribute("value").trim());  
        
         //Select if aleady not selected  
         if (!(number_of_checkbox.get(i).isSelected())) {  
           number_of_checkbox.get(i).click();  
         } else {  
           //De-select the checkbox  
           number_of_checkbox.get(i).click();  
         }  
       } //Checking Radio button  
       else if (number_of_checkbox.get(i).getAttribute("type").trim().equalsIgnoreCase("radio")) {  
         // //Print the Check box count with value  
         System.out.println("Radio  = " + i + " " + number_of_checkbox.get(i).getAttribute("value").trim());  
         //Select if aleady not selected  
         if (!(number_of_checkbox.get(i).isSelected())) {  
           number_of_checkbox.get(i).click();  
         }  
       }  
       // Pause so that you can see the results.  
       Thread.sleep(3000);  
     }  
 //close firefox browser    
     driver.close();  
   }  
 }  

How to check visibility or appearance or presence of web elements in Selenium Webdriver using Java

Sometime We don't know about the element visible or no that reason we need to check web element is present or visible or enabled or disabled etc. Selenium Webdriver facilitates the user with some methods to check the visibility of the web elements. isSelected(), isEnabled() and isDispalyed() etc methods are used to determine the visibility scope for the web elements.

driver.findElements(By.id("email")).size() ! =0
We need to perform a action based on a specific web element being present or not on the web page. We can return true only when the size of elements is greater than Zero. That mean there exists at least one element.
driver.findElements(By.id("email")).size()>0; or
driver.findElements(By.id("email")).size() ! =0;


isEnabled
Below is the syntax which is used to check if the element is enabled or not
WebElement element = driver.findElement(By.id("email"));
element.isEnabled();


isDisplayed
Below is the syntax which is used to check if the element is displayed or not. It returns false when the element is not present in DOM.
WebElement element = driver.findElement(By.id("email"));
element.isDisplayed();


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

public class PresentElement {

public static void main(String[] args) {
// create objects and variables instantiation     
WebDriver driver = new FirefoxDriver();
// maximize the browser window       
driver.manage().window().maximize();
// launch the firefox browser and open the application url     
driver.get("http://www.facebook.com");
//Set  timeout      
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//To check Element Present
if (driver.findElements(By.id("email")).size() != 0) {
    System.out.println("Element is Present");
} else {
    System.out.println("Element is Absent");
}
//or
if (driver.findElements(By.id("paaswprd")).size() > 0) {
    System.out.println("Element is Present");
} else {
    System.out.println("Element is Absent");
}

//To check Visible
if (driver.findElement(By.id("u_0_v")).isDisplayed()) {
    System.out.println("Element is Visible");
} else {
    System.out.println("Element is InVisible");
}

//To check Enable
if (driver.findElement(By.id("u_0_1")).isEnabled()) {
    System.out.println("Element is Enable");
} else {
    System.out.println("Element is Disabled");
}
// fetch the source of the web page and save it into a string variable
String title = driver.getPageSource();
//To check text present
if (title.contains("Sign Up")) {
    System.out.println("Text is present");
} else {
    System.out.println("Text is absent");
}

//close firefox browser  
driver.close();
    }

}