Monday 14 October 2019

CSS Selector selenium

What is CSS?
         CSS stands for Cascading Style Sheets. CSS describes how the web elements present/displayed on web page/screen and look and feel of a web page. Formatting of a webpage. 
 
Why CSS Selector?
         CSS refers Cascading style sheet describes the look and feel of a website/web application by maintaining standard formatting for web text, buttons, colouring etc...
So, CSS is uniform to all the pages of a web application and same web application is displayed on different browser. so it uniform to all the web browsers unlike XPATH.

  • Handling of XPATH is different with different browser. XPATH engines which handles xpath is different with different browsers.
  • So CSS has advantages over xpath as web application is uniform with different browsers so same CSS locator's will work on different browsers but it is not the same case with xpath means- xpath calculate on IE browsers may/may not work on chrome or firefox browser.
  • But Xpath has much more capabilities (like parent, ancestor, self, descendant, preceding-sibling etc..) than css.
Different Format of CSS Selectors:
  1. BY Id  ( # )
  2. By Class ( . )
  3.  Sibling (following) ( + )
  4. Immediate Child ( > )
  5. Any Child (Child, Grandchild etc..)    (  SPACE )
  6. By Attribute
  7. Starts-With ( ^= )
  8. Ends-With  ( $= )
  9. Contains     ( *= )
  10. nth-child(index)
  11. nth-of-type(index) 
Let's see one-by-one:
For above css formatters from 1 to 09 we will use facebook.com as reference website / web application where we used to identify/locate control's/web elements by using CSS selectors.
 

1.  By Id
             Here For Id CSS uses "#" as a convention symbol.
      e.g.
        https://www.facebook.com/

      " input#email "    =>Here we are identifying email Textbox.
      " input#pass "      => Here, we are identifying password textbox.
      " input#u_0_4 "   => Here, we are identifying "Log In" button.

       Here, we are strictly stating we have to identify only input tag which is having mentioned ID.
   
      or  we can use without tag name aswell like below examples-

      " #email "          => Here we are identifying email Textbox.
      " #pass "            => Here, we are identifying password textbox.
      " #u_0_4 "         => Here, we are identifying "Log In" button.

     but in this case it will search any control/tag which is having mentioned id.



2. By Class
          For class CSS uses " . " (dot) as a convention symbol.
Sometime a control / web elements can have more than one class applied on it (class name seperated by space ). Example- one class specifies height & width another may specifies color and other may specifies formatting. So in such case we have to remove space by adding " ." (dot) in between multiple class names.
      e.g.
        https://www.facebook.com/
       " input.inputtext.login_form_input_box " => Here it will return email as well as password
                                                                             Textbox both control/web element.
   
       or
    
       " .inputtext.login_form_input_box " => Here it will return email as well as password
                                                                             Textbox both control/web element.
 

 Note:       
      Same class can be applied on multiple controls so here the chance of getting only one control is minimal  than getting multiple controls. If we use driver.findElement() then it will retun first control always in search from Top to Bottom in a HTML document.

     " input.inputtext._58mg._5dba._2ph- "  => It will identify FirstName Text box from create 
                                                                          account form.
    or
    
  
     " .inputtext._58mg._5dba._2ph- "  => It will identify FirstName Text box from create 
                                                                  account form.


 3. Sibling (following) ( + ):
                   
                          To select/identify the control those are  siblings to each other. By considering one of the sibling as a reference we can identify other sibling by appending ( + ).

         e.g.
        Here we have to identify Text box like (First Name, mobileNumber, New Password, Birthday)

    
  •      " div#reg_form_box>div+div "   => It will identify Mobile Number or email address       
                                                                        textbox (div)

               Here div# reg_form_box indicate the create account division 
     
              div#reg_form_box>div indicates FirstName & Last Name complete row (division) by 
                                                    considering this div as reference element we will identify other 
                                                    sibling elements like- MobileNumber, New Password  and Birthday 
                                                    etc..

   
  •      " div#reg_form_box>div+div+div#u_0_10 "      => Identify "Gender" Division.
  •     " div#reg_form_box>div+div#password_field "  => Identify "New Password" Division. 

  •     " div#reg_form_box>div+div#birthday_wrapper " => Identify "Birthday" Division.
  •    " div#reg_form_box>div+div#u_0_14 "                 => Identify "Terms, Data Policy" Text.



4. Immediate Child ( > )

        Identify an immediate child of any parent control / element. CSS selector uses convention ( > ).

       e.g.
      Lets we want to identify login table (Top most login form)

  •  " table>tbody>tr "    => Get the table row indicating Email or Phone & Password TextBox label


  •  " form#login_form>table " => Identify table tag which is the child of login form.
  • " table>tbody>tr>td>input#email " => Locate email Text Box
  • " table>tbody>tr>td>input#pass " => Locate passord Text Box.  

  • " select#day>option "  => Locate/get first option from "day" drop down list.



5. Any Child (Child, Grandchild etc..)      
              
            In CSS Selector (SPANCE) is used to idenify child, any child or grand child of a given            
 element / control / tag. In this we will consider ant tag as a parent or reference control and we will search any child / grand child respective to that element or reference control/tag/element.

          e.g.
        
  •    " table input#email "            => Identify email or phone text box
  •    " table input#pass "             => Locate password text box. 
  •   " div#reg_form_box input#u_0_m "  => Identify First Name from create new account form
  •   " div#reg_form_box input#u_0_s "   => Identify mobile number from create new account 
 
 
6. By Attribute
          
          Like wise XPATH CSS Selector can also identify control with the help of attribute. The only 
           difference is xpath uses ( @ ) as a prefix to attribute name.
   
         e.g. 
  •   " input[name = 'email' ] "    => Identify Email or Phone  Textbox.
  •   " input[id = 'pass' ] "           => Identify Password  Textbox.
  •   " input[id = 'u_0_n'] "        => Identify First Name Text Box from Create new Account
  •   " input[id='email'][type='email] " => Identify Email or Phone  Textbox.
 
 
7.  Starts-With ( ^= )
            In CSS Selector starts-with denoted as ( ^= ) like wise XPATH has start-with() method.
It is used to identify any control whose any property/attribute value starts with some fixed character/number. Starting few characters should be fixed ending character can be vary. 
It is used to handle dynamic control on a page.

           e.g.
  •   " input[id^='ema'] "             => Identify Email or Phone  Textbox.
      OR

  •   " input[id^='ema'][type='email'] " => Identify Email or Phone Textbox.
  •   " input[name^= 'first']  "    => Identify First Name Text Box from Create new Account.
  •   " button[name ^= 'web'] "  =>  Identify Sign Up  buttoon from Create new Account.
       OR
  •   " [name^= 'web']                =>    Identify Sign Up  buttoon from Create new Account.
 
 
8. Ends-With  ( $= )
       In CSS Selector ends-with denoted as ( $= ) like wise XPATH has ends-with() method.
It is used to identify any control whose any property/attribute value ends with some fixed character/number. Ending few characters should be fixed buts starting or mid characters can be vary. 
It is used to handle dynamic control on a page.
      e.g.
  •    "input[name $= 'passwd__']"    => Identify New Password from create new account form.
  •    "input[name $= 'email__']"       => Identify Mobile Number or Email address.
  •    "select[name $= '_day']"           =>  Identify Birthday Day from create new account.
  •    "button[name $= 'submit']         => Identify Sign Up button from create new account.


9. Contains     ( *= )
             
            In CSS Selector contains denoted as ( $= ) like wise XPATH has contains() method.
It is used to identify any control whose any property/attribute value contains some fixed character/number. Starting or Ending few characters should be vary buts middle few characters can be fixed. 
It is used to handle dynamic control on a page.
           e.g.
  •    "input[name *= 'passwd']"    => Identify New Password from create new account form.
  •    "input[name $= '_email_']"       => Identify Mobile Number or Email address.
  •    "select[name $= 'day_']"           =>  Identify Birthday Day from create new account.
  •    "button[name $= 'sub']         => Identify Sign Up button from create new account.
 Now so far, for above CSS selector we have used https://www.facebook.com. to identify the control.



10. nth-child(index)

      nth-child(index) method is used to select/get specified index child element.  But the specified index element should be same as mentioned before colon ( : ).

      e.g.
         
Scenario-1:

<ul>
      < li > Avinash-1 < /li >
      < li > Avinash-2 < /li >
      < li > Avinash-1 < /li >
< / ul >
         ul>li:nth-child(2)          => Here we want to select 2-nd li element which is the child of ul. 
          

 Scenario-2:

<ul>
      < li > Avinash-1 < /li >
      <input type="text" id=i1 />
      < li > Avinash-2 < /li >
       <input type="text" id=i2 />
      < li > Avinash-1 < /li >
< / ul >
         ul>li:nth-child(2)          => Here we want to select 2-nd li element which is the child of ul. But here child of UL with index=2 is <input> tag so here input tag is not same type of li type both are different tag. So here you will get exception as- (If specified index element type is not same as mentioned before the ( : ) colon  then you will get) org.openqa.selenium.NoSuchElementException.

Note:
        It means nth-child(index) method check the type of specified index with mentioned in locator befor the ( : ) colon.


11. nth-of-type(index) 

          nth-of-type(index)  is also ued to select the child of specified index. But nth-of-type removes the other tags(child) other than specified tag (child) in selector that is to be select and make list of the specified child tags. Among the list of child elements it will get the specified index element. If the specified index is there then it will return the specified child elements.
If the specified index is not there (out of index ) then it will through exception as- org.openqa.selenium.NoSuchElementException 

        e.g.
       
         <html>
             <body>
                 <ul>
                      <li> Avinash-1 </li>   
                      <input type="text" id=i1 />

                      <li> Avinash-2 </li>
                     <input type="text" id=i2 />

                     <li> Avinash-3 </li>
                     <input type="text" id=i3 />
   
                     <input type="text" id=i4 />
             </ul>
      </body>
</html>


if we want select second li elements then methods looks like as -


  •    "ul>li:nth-of-type(2)" =>  It will removes the input tags from above example and make the list of remaining li  tags and from that list it will get the element with specified index if it is there . In this case it will return -
                                                                <li> Avinash-2 </li>
  •    "ul>li:nth-of-type(4)" => Here after removal of input tags (those are other than li tags ) it will make the list as-
                                                               <li> Avinash-1 </li>   
                                                               <li> Avinash-2 </li>
                                                               <li> Avinash-3 </li> 
         from this list it will check the specified index is there or not. If the specified index is not present then it will return-     
         org.openqa.selenium.NoSuchElementException 


References: