Tuesday, April 3, 2018

CSS Selectors in Selenium WebDriver with Examples

CSS Selector is the combination of an element selector and a selector value which identifies the web element within a web page. The composite of element selector and selector value is known as Selector Pattern. Selector Pattern is constructed using HTML tags, attributes and their values. The central theme behind the procedure to create CSS Selector and Xpath are very much similar underlying the only difference in their construction protocol.
CSS Selectors in Selenium WebDriver with Examples

In this post we are going to discuss how to use css selector in selenium WebDriver java. Most of the automation testers believe that using CSS selectors makes the execution of script faster compared to XPath locator. CSS Selector locator is always the best way to locate elements on the page. CSS is always same irrespective of browsers.


To learn more about CSS Sector, do visit the below page :
https://www.w3schools.com/cssref/css_selectors.asp

Some benefits of using CSS Selectors :
  1. CSS Selector is faster (especially in IE).
  2. CSS Selector more readable.
  3. In terms of performance, CSS perform well as compared to XPATH.
NOTE : While selecting an element make sure that element should be unique, descriptive and unlikely to change.

Syntax for CSS Selector in selenium WebDriver : 
driver.findElement(By.cssSelector("input[class='username']")).sendKeys("skptricks-3"); 
To identify the web element using css selector, we need to call cssSelector() method.

Check out below web page link, we are going to use this link for CSS Selector demonstration : 
DEMO LINK :

CSS selector locator in selenium WebDriver 

Below are different type of techniques helps to find an element using css selector in selenium WebDriver :

Locating Elements by its Attributes

In this example we are going to locate "Name" field of  user registration page by its attribute using CSS Selector.

Web Element :
<input type="text" id="regUsername" name="username" class="username" autocomplete="off">

Following are the possible way to uniquely identify the "Name" Field.
  • input[id="regUsername"]
  • input[name="username"]
  • input[class="username"]
Syntax:
element_name[<attribute_name>='<value>']

Refer the below screenshot, which will help you to identify the element from the webpage.

Script :

package demoPackage;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumDemo {

 public static WebDriver driver;
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  System.out.println("Launching the chrome driver  ");  
    
  // Set the chrome driver exe file path
  System.setProperty("webdriver.chrome.driver","E:\\selenium_sumit\\chromedriver_win32_2.36\\chromedriver.exe");  
  
  // Instantiate the chrome driver
  driver = new ChromeDriver();
  
  // wait time
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
  // set the browser URL in get() to load the webpage
     driver.get("https://skptricks.github.io/learncoding/selenium-demo/login%20registration%20page/Register.html");  
     
     // locating an elements by its Attributes
     //driver.findElement(By.cssSelector("input[id='regUsername']")).sendKeys("skptricks-1"); 
     //driver.findElement(By.cssSelector("input[name='username']")).sendKeys("skptricks-2"); 
     driver.findElement(By.cssSelector("input[class='username']")).sendKeys("skptricks-3"); 

 } 

}

Locating Elements by ID

In this example we are going to locate "Name", "Email" and "Password" field of  user registration page by its ID using CSS Selector.

Web Element :
<input type="text" id="regUsername" name="username" class="username" autocomplete="off">
<input type="text" id="regEmail" name="emailid" class="emailid" autocomplete="off">
<input type="password" id="regPassword" name="userpassowrd" class="password" autocomplete="off">

Locating the "Name", "Email" and "Password" field by its ID using below CSS Selector :
  1. input#regUsername  OR  #regUsername
  2. input#regEmail  OR    #regEmail 
  3. input#regPassword  OR   #regPassword
Syntax:
element_name#id_value

Refer the below screenshot, which will help you to identify the element from the webpage.

Script:
package demoPackage;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumDemo {

 public static WebDriver driver;
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  System.out.println("Launching the chrome driver  ");  
    
  // Set the chrome driver exe file path
  System.setProperty("webdriver.chrome.driver","E:\\selenium_sumit\\chromedriver_win32_2.36\\chromedriver.exe");  
  
  // Instantiate the chrome driver
  driver = new ChromeDriver();
  
  // wait time
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
  // set the browser URL in get() to load the webpage
     driver.get("https://skptricks.github.io/learncoding/selenium-demo/login%20registration%20page/Register.html");  
     
     // locating an elements by its ID
     driver.findElement(By.cssSelector("input#regUsername")).sendKeys("sumit"); 
     driver.findElement(By.cssSelector("input#regEmail")).sendKeys("sumit@gmail.com"); 
     driver.findElement(By.cssSelector("input#regPassword")).sendKeys("1234567890"); 

 } 

}

Locating Elements by Class

In this example we are going to locate "Name", "Email" and "Password" field of  user registration page by its Class using CSS Selector.

Web Element :
<input type="text" id="regUsername" name="username" class="username" autocomplete="off">
<input type="text" id="regEmail" name="emailid" class="emailid" autocomplete="off">
<input type="password" id="regPassword" name="userpassowrd" class="password" autocomplete="off">

Locating the "Name", "Email" and "Password" field by its Class using below CSS Selector :
  1. input.username  OR  .username
  2. input.emailid   OR  .emailid
  3. input.password  OR  .password 
Syntax:
element_name.class_value

Refer the below screenshot, which will help you to identify the element from the webpage.

Script :
package demoPackage;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumDemo {

 public static WebDriver driver;
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  System.out.println("Launching the chrome driver  ");  
    
  // Set the chrome driver exe file path
  System.setProperty("webdriver.chrome.driver","E:\\selenium_sumit\\chromedriver_win32_2.36\\chromedriver.exe");  
  
  // Instantiate the chrome driver
  driver = new ChromeDriver();
  
  // wait time
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
  // set the browser URL in get() to load the webpage
     driver.get("https://skptricks.github.io/learncoding/selenium-demo/login%20registration%20page/Register.html");  
     
     // locating an elements by its ID
     driver.findElement(By.cssSelector("input.username")).sendKeys("sumit"); 
     driver.findElement(By.cssSelector("input.emailid")).sendKeys("sumit@gmail.com"); 
     driver.findElement(By.cssSelector("input.password")).sendKeys("1234567890"); 

 } 

}

Locating elements by multiple classes

In this example we are going to locate "button" field of  user registration page by its Class using CSS Selector.
Web Element :
<input type="submit" class="button style1 style2 style3" name="submitregistrationform" value="Register">

Syntax:
elementName.class1.class2.class3 or .class1.class2.class3

Locating the input "Button" field by its multiple class using below CSS Selector :
  1. input.button
  2. input.button.style1
  3. input.button.style1.style2
  4. input.button.style1.style2.style3
  5. .button.style1.style2.style3
  6. .style1.style2.style3
  7. .style2.style3
  8. .button
Refer the below screenshot, which will help you to identify the element from the webpage.


Script :
package demoPackage;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumDemo {

 public static WebDriver driver;
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  System.out.println("Launching the chrome driver  ");  
    
  // Set the chrome driver exe file path
  System.setProperty("webdriver.chrome.driver","E:\\selenium_sumit\\chromedriver_win32_2.36\\chromedriver.exe");  
  
  // Instantiate the chrome driver
  driver = new ChromeDriver();
  
  // wait time
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
  // set the browser URL in get() to load the webpage
     driver.get("https://skptricks.github.io/learncoding/selenium-demo/login%20registration%20page/Register.html");  
     
     // locating an elements using css selector
     driver.findElement(By.cssSelector("input.button.style1.style2")).click();
     

 } 

}


Locating Elements by Class and Attribute

In this example we are going to locate "Name" field of  user registration page by its Class and attribute element using CSS Selector.
Web Element :
<input type="text" id="regUsername" name="username" class="username" autocomplete="off">

Syntax:
elementName.class[attributeName=’value’]

Locating the "Name" field by its class and attribute element using below CSS Selector :
input.username[name="username"]
OR
.username[name="username"]

Refer the below screenshot, which will help you to identify the element from the webpage.

Script:
package demoPackage;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumDemo {

 public static WebDriver driver;
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  System.out.println("Launching the chrome driver  ");  
    
  // Set the chrome driver exe file path
  System.setProperty("webdriver.chrome.driver","E:\\selenium_sumit\\chromedriver_win32_2.36\\chromedriver.exe");  
  
  // Instantiate the chrome driver
  driver = new ChromeDriver();
  
  // wait time
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
  // set the browser URL in get() to load the webpage
     driver.get("https://skptricks.github.io/learncoding/selenium-demo/login%20registration%20page/Register.html");  
     
     // locating an elements using css selector
     driver.findElement(By.cssSelector("input.username[name='username']")).sendKeys("skptricks");
     

 } 

}

Locating Elements with more than one Element

In this example we are going to locate "Name" field of  user registration page with more than one element using CSS Selector.
Web Element :
<input type="text" id="regUsername" name="username" class="username" autocomplete="off">

Syntax:
elementName[attribute1=’value1’][attribute2=’value2’]…[attributeN=’valueN’]

Locating the "Name" field with more than one element using below CSS Selector :
input[id="regUsername"][name="username"]
OR
input[id="regUsername"][name="username"][class="username"]
OR
[name="username"][class="username"]
OR
[id="regUsername"][name="username"][class="username"]

Refer the below screenshot, which will help you to identify the element from the webpage.

Script:
package demoPackage;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumDemo {

 public static WebDriver driver;
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  System.out.println("Launching the chrome driver  ");  
    
  // Set the chrome driver exe file path
  System.setProperty("webdriver.chrome.driver","E:\\selenium_sumit\\chromedriver_win32_2.36\\chromedriver.exe");  
  
  // Instantiate the chrome driver
  driver = new ChromeDriver();
  
  // wait time
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
  // set the browser URL in get() to load the webpage
     driver.get("https://skptricks.github.io/learncoding/selenium-demo/login%20registration%20page/Register.html");  
     
     // locating an elements using css selector
     driver.findElement(By.cssSelector("input[id='regUsername'][name='username']")).sendKeys("skptricks");
     

 } 

}

Locating Child Elements by Element Name

In this example we are going to Locating direct child or sub child element. Here we are referring "Name" field. 
Web Element :
<form method="post" action="" name="register">
<label>Name</label>
<input type="text" id="regUsername" name="username" class="username" autocomplete="off">
--------------
--------------
</form>

Syntax:
CSS-of-Parent Element  > elementName

Locating the child element ( "Name" field of user registration page ) by element name.
  • form>input.username
Refer the below screenshot, which will help you to identify the element from the webpage.



Script:
package demoPackage;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumDemo {

 public static WebDriver driver;
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  System.out.println("Launching the chrome driver  ");  
    
  // Set the chrome driver exe file path
  System.setProperty("webdriver.chrome.driver","E:\\selenium_sumit\\chromedriver_win32_2.36\\chromedriver.exe");  
  
  // Instantiate the chrome driver
  driver = new ChromeDriver();
  
  // wait time
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
  // set the browser URL in get() to load the webpage
     driver.get("https://skptricks.github.io/learncoding/selenium-demo/login%20registration%20page/Register.html");  
     
     // locating an elements using css selector
     driver.findElement(By.cssSelector("form>input.username")).sendKeys("skptricks");
     

 } 

}

Locating Nth Child Elements by Element type

In this example we are going to locate nth elements using nth-of-type(N) function of CSS Selector.
Web Element :
<form method="post" action="" name="register">
<label>Name</label>
<input type="text" id="regUsername" name="username" class="username" autocomplete="off">
<input type="text" id="regEmail" name="emailid" class="emailid" autocomplete="off">
--------------
--------------
</form>
Syntax:
CSS-of-Parent-Element elementName:nth-of-type(N)

Locating  "Name" and "email" Field using nth-of-type(N) function :
Locating Name Field : 
  • form input:nth-of-type(1)
Locating Email Field :
  • form input:nth-of-type(2)
package demoPackage;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumDemo {

 public static WebDriver driver;
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  System.out.println("Launching the chrome driver  ");  
    
  // Set the chrome driver exe file path
  System.setProperty("webdriver.chrome.driver","E:\\selenium_sumit\\chromedriver_win32_2.36\\chromedriver.exe");  
  
  // Instantiate the chrome driver
  driver = new ChromeDriver();
  
  // wait time
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
  // set the browser URL in get() to load the webpage
     driver.get("https://skptricks.github.io/learncoding/selenium-demo/login%20registration%20page/Register.html");  
     
     // locating an elements using css selector
     driver.findElement(By.cssSelector("form input:nth-of-type(1)")).sendKeys("skptricks");
     driver.findElement(By.cssSelector("form input:nth-of-type(2)")).sendKeys("skptricks@gmail.com");
     

 } 

}

Locating First Child Element by Element Name

In this example we are going to locate first element of form that is "Name" Field using :first-child selector.

Syntax:
CSS-of-Parent-Element  elementName:first-child

Locating First element using :first-child selector.
  • form input:first-child

Refer the below screenshot :

Locating Last Child Element by Element Name

In this example we are going to locate last element of form that is "Password" Field using :last-child selector.

Syntax:
<CSS of Parent Element><space><elementName>:last-child

Locating last element using :last-child selector.
  • form input:last-child
Refer the below screenshot :


Locating Elements by Prefix of the (starts-with) Attribute Value

In this example we are going to locate an element using start with prefix attribute value. Considering "Name" Field of user registration page for this demo. This will help to match the starting characters of attribute value.
Web Element :
<input type="text" id="regUsername" name="username" class="username" autocomplete="off">

Syntax:
elementName[attributeName^=’prefix-of-the-value’]

Locating "Name" Field using start with prefix attribute value using CSS Selector :
input[name^="userna"]
OR
input[id^="regU"]

NOTE : ^= Match a prefix (This indicate the match prefix characters form attribute value)


Refer the below screenshot :


Locating Elements by Suffix of the (ends-with) Attribute Value

In this example we are going to locate an element using end with suffix attribute value. Considering "Name" Field of user registration page for this demo.This will help to match the ending characters of attribute value.
Web Element :
<input type="text" id="regUsername" name="username" class="username" autocomplete="off">

Syntax :
elementName[attributeName$=’suffix-of-the-value’] or *[attributeName$=’suffix-of-the-value’]

Locating "Name" Field using end with prefix attribute value using CSS Selector :
input[id$="name"]
OR
input[class$="name"]

NOTE : $= Match a suffix (This indicate the match suffix characters form attribute value)

Refer the below screenshot :

Locating Elements containing part of the Attribute Value

This method helps to match the substring character from the attribute value. Here we are locating "Name" Field of user registration page.
Web Element:
<input type="text" id="regUsername" name="username" class="username" autocomplete="off">

Syntax:
elementName[attributeName*=’part-of-the-value’]

Locating the Name Field with help of substring match :
input[id*="ser"]
OR
input[class*="ser"]

NOTE : *= Match a substring  (This indicate the match substring characters form attribute value)

Refer the below screenshot :


This is all about CSS Selector, which helps to locating an web element from the web page with the help of selenium webdriver. In case of any question, please do comment in comment box below.


No comments:

Post a Comment