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:

 

Wednesday, 12 December 2018

Reading csv files and comparing it

package selenium;

import java.util.ArrayList;
import java.util.HashMap;

public class CSVComparisonMain {

private static ArrayList<String> keys_Source=null;
private static ArrayList<String> keys_Destination = null;
private static HashMap<String, ArrayList> header_Values_Source;
private static HashMap<String, ArrayList> header_Values_Destination;

public static void main(String[] args) throws Exception
{
CSVFIleReader source_Obj = new CSVFIleReader("C:\\Avinash\\source.csv", "EVENT_CD");
source_Obj.readCSVFIle();
keys_Source = source_Obj.keys;
header_Values_Source = source_Obj.header_Values;


CSVFIleReader destination_Obj = new CSVFIleReader("C:\\Avinash\\Destination.csv", "EVENT_CD");
destination_Obj.readCSVFIle();
keys_Destination = destination_Obj.keys;
header_Values_Destination = destination_Obj.header_Values;

System.out.println("Comparison Starts.............!!!");


for (String key : keys_Source) {
if(header_Values_Destination.containsKey(key))
{
ArrayList source_Values =  header_Values_Source.get(key);
ArrayList destination_Values =  header_Values_Destination.get(key);
for (Object value : source_Values)
{
if(!destination_Values.contains(value))
{
throw new Exception("Source file Value: "+value+" is not matched in target file value: "+value);
}
}

}
else
{
throw new Exception ("Exception occured while comparing .csv file.......Key: "+ key +" not found in target file");
}
}
}

}


package selenium;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

public class CSVFIleReader
{

BufferedReader csvReader = null;
String filePath = null;
String key = null;
public String delimiter = null;
int keyIndex = -1;

HashMap<String, ArrayList> header_Values = null;
ArrayList<String> keys =null;
ArrayList<String> values = null;

public CSVFIleReader(String filePath , String key)
{
this.filePath = filePath;
this.key = key;
header_Values = new HashMap<>();
keys = new ArrayList<>();
values = new ArrayList<>();
}


public void readCSVFIle()
{
String line = null;
int header = 0;
try
{
csvReader = new BufferedReader(new FileReader(filePath));
while((line=csvReader.readLine()) != null)
{
String delimit = getDelimiter(line);
System.out.println(line);
if(delimit != null)
{
++header;
generateKeyValuePair(line,header);
}
}
printCSVFile();
csvReader.close();
csvReader = null;
}
catch(Exception e)
{

}
}


public void generateKeyValuePair(String line, int header)
{
ArrayList<String> values = new ArrayList<>();
try
{
if(delimiter.equalsIgnoreCase("pipe") || delimiter.equalsIgnoreCase("comma"))
{
String[] words = line.split("\\|");
if(words.length > 1)
{
for (String value : words)
{
values.add(value);
}
}
if(words.length <= 1)
{
words = line.split("\\,");
if(words.length > 1 )
{
for (String value : words)
{
values.add(value);
}
}
else
throw new Exception("Exception occured while parsing .csv file. Delilmiter is not valid");
}
else
{
throw new Exception("Exception occured while parsing .csv file. Delilmiter is not valid");
}
if(header == 1) //It Means first line is header
{
if(values.contains(key))
{
keyIndex = values.indexOf(key);
}
}

keys.add(values.get(keyIndex));
header_Values.put(values.get(keyIndex).toString(), values);


}
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.exit(0);
}
}

public String getDelimiter(String line)
{
String words[]  = line.split("//|");
if(words.length>0)
{
delimiter = "pipe";
}
else
{
words = line.split("//,");
if(words.length > 0)
{
delimiter = "comma";
}
}
return delimiter;
}

public void printCSVFile()
{
Set<Entry<String, ArrayList>> entrySet = header_Values.entrySet();
for (Entry<String, ArrayList> entry : entrySet)
{
System.out.print(entry.getKey() );
ArrayList values = entry.getValue();
for (Object value : values) {
System.out.print("         "+value.toString());

}
System.out.println();
}
}


public static void main(String[] args)
{
CSVFIleReader obj = new CSVFIleReader("C:\\Avinash\\Temp.csv", "EVENT_CD");
obj.readCSVFIle();

}

}







Saturday, 11 August 2018

Handling multiple windows in selenium

Handling Window Pop Up In Selenium: 

There may be a situation while doing automation where we need to handle multiple window popup or where we need to go to appropriate window among multiple windows at run time. Selenium code /automation get focused on default/parent window.
E.g If you navigate or go to Naukri.com url then you will get multiple window pop up only when if you haven't disable pop up option.

Here, How do we know that it is a window popup or java script pop up or Jquery/Normal pop up.

Window Pop up:

           Window pop up has minimize, maximize and close button like any normal browser has.
            driver.switchTo().window("windowName);
            driver.switchTo().window();
         
           Here driver referes to webDriver object -

           WebDriver driver = new ChromeDriver();

Java Script Pop Up: 

           Java script pop up doesn't have minimize or maximize button/option also focus is only on java script pop up page. you can't ignore the java script popup but window pop up you can ignore it and perform operation on any other windows.

Ways to Handle Window Pop Up in Selenium:
    
           Selenium webdriver assign unique id (alpha numeric ) to every window to identify uniquely. The alpha numeric id (unique id) is called "Window Handle" in selenium.

How to get Window Handle:

          String handle = driver.getWindowHandle();

If there are multiple window gets opened when you click on any link,button etc... then to get "window Handle" of each window -

          Set<String> windowHandles = driver.getWindowHandles();

"getWindowHandles()" : method return window handle (unique id for each opened window) so that the return type is set. Because set will not contain duplicate elements so here getWindowHandles return unique id/window handles for each winodw and stored in Set.

How to switch to correct / appropriate window:

          Basically there are two ways to switch to appropriate window.

  1. By using windowName
         driver.switchTo().window( "windowName" );
        or
     
     2.  To get current/parent/default window handle:

        String handle = driver.getWindowHandle();
        driver.switchTo().window( handle  );

        or

        Set < String > windowHandles = driver.getWindowHandles();
        for(String handle : windowHandles )
         {
             driver.swicthTo().window( handle ); 
        }


Example:





Sunday, 24 June 2018

Spinner To handle in Selenium











Firstname Lastname Age Select
Jill Smith 50
Eve Jackson 94
John Doe 80

Handling Spinner in Selenium

Handling Spinner In Selenium:

       To handle Spinner in selenium we have to use Synchronization concept with the help of wait.
It is always best to use Explicit Wait  on each control. so we have been  using Explicit Wait in our below example.

We are handling Spinner from  Spinner Link  this link. Click on it.

Basically above link contains two buttons-
1- Show Spinner
2- Hide Spinner

Show Spinner: When we click "Show Spinner" button then spinner is moving with 5-second timeout once 5-Second elapsed data will be loaded in tabular format.

Hide Spinner: When we click on "Hide Spinner" button It will hide the Spinner as well as tabular data (if tabular data is present/already loaded on page)

Intention of having such scenario/example is correlating with real time scenario- where when user click on any button then data is fetching from database in mean time spinner is running on page and  block the page activity once the data is ready spinner will disappear from screen.


Explicit Wait:
  1. WebdriverWait
  2. FluentWait
In below example we have used fluent wait with Function which is parameter to until function.
In example we have passed Webdriver object and By class object which is the locator path to spinner to function - waitTillSpinnerDisable(WebDriver driver, By by)

apply(): We have override apply method which will return either true or false. In example  it will return TRUE  in case of spinner is disappear (i.e. style.display="none") else it will return FALSE in case of timeout or style.display="block".

Once the Spinner is disappear it will load the data in tabular format and we have to parse the table where we need to select check on the basis of if  Name & Surname gets matched with tabular data where we passed Name & Surname at  execution time.


Execution Steps:
  1. Load the page
  2. Click on Show Spinner button
  3. Pass the driver object and locator for Spinner to waitTillSpinnerDisappear method
  4. Check the method return type if above method waitTillSpinnerDisappear return true then
  5. Parse the table with condition Name & Surname gets matched if match then select respective check box.
Download:

Download Spinner.html file form below link :- 


or 

Refer to page- 




Java Code:


Sunday, 17 June 2018

Handling Dynamic Web Tables Using Selenium


Handling Dynamic Web Tables Using Selenium by using XPATH

     In below example we have consider Application Under Test from url as- https://www.redmine.org/issues . 
Where this url/application contains issues reported by users etc.. All the reported issues are in 
tabular format. In below example we have used xpath with multiple condition in a single xpath.
Also we have passed java variable as a argument to xpath at runtime.
        Here, we have to pass issueId and status as a argument below code will check issueId and respective 
status code is matched or not with table data if not it will click on next page and searched 
the given condition with table data it will search until it will find at least one of the record. 
Once the record found then execution will stop.


Screenshot of the Page:


Java Code:

package seleniumCode;

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;
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;

public class WebTable 
{
 public static void main(String[] args) 
  {
     WebDriver driver = null;  
     List<WebElement> listWebElement = null;
     boolean flag = false;
  
    driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("https://www.redmine.org/issues");
    
    String issueId = "28232";
    String status = "New";
  
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    do
     {   
 listWebElement = driver.findElements(By.xpath("//table[@class='list issues']
          //tr//a[text()='"+issueId+"']//ancestor::td//following-sibling::
         td[text()='"+status+"']//preceding-sibling::td/input"));
   
 for (WebElement element : listWebElement) 
 {
  System.out.println(element.getAttribute("value"));
  element.click();
  flag = true;
  break;
 }
  
 if(flag==true)
   break;
 if(flag == false || listWebElement.size()==0)
  {
    //Page Down
    Actions ac = new Actions(driver);
    ac.moveToElement(driver.findElement(By.cssSelector("a.atom"))).build().perform();
    try 
             {
  Thread.sleep(2000);
       } 
           catch (InterruptedException e) 
            {
       // TODO Auto-generated catch block
  e.printStackTrace();
     }    
    
     driver.findElements(By.cssSelector("a.next")).get(0).click();
 }
  
      }while(driver.findElements(By.cssSelector("a.next")).size()>0 || flag==false);
   } 
 
}




References:  https://www.redmine.org/issues

See Also: