Quick Contact

    Handling Cookies

    What Is An HTTP Cookie And How It Works?

    HTTP Cookie is also called as a web cookie, a browser cookie or an Internet cookie. It is nothing but a text file present in the web browser of the client machine or PC that stores a small piece of information received from a website as a key-value pair when the user does the web browsing.
    When a user loads that website again, the browser sends back the stored cookie to the server that notifies it about the user’s past activities. HTTP Cookies store not only the user’s browsing history but also the shopping cart information for an online store, login user ids and passwords and other related information.

    Why Handle Cookies in Selenium?

    Each cookie is associated with a name, value, domain, path, expiry, and the status of whether it is secure or not. In order to validate a client, a server parses all of these values in a cookie.

    When testing a web application using selenium web driver, you may need to create, update or delete a cookie.

    For example, when automating Online Shopping Application, you many need to automate test scenarios like place order, View Cart, Payment Information, order confirmation, etc.

    If cookies are not stored, you will need to perform login action every time before you execute above listed test scenarios. This will increase your coding effort and execution time.

    The solution is to store cookies in a File. Later, retrieve the values of cookie from this file and add to it your current browser session. As a result, you can skip the login steps in every Test Case because your driver session has this information in it.

    The application server now treats your browser session as authenticated and directly takes you to your requested URL.

    Introducing Web Driver

    The primary new feature in Selenium 2.0 is the integration of the WebDriver API. WebDriver is designed to provide a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API. Selenium-WebDriver was developed to better support dynamic web pages where elements of a page may change without the page itself being reloaded.
    WebDriver’s goal is to supply a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems

    Selenium WebDriver Query Commands For Cookies

    Using Selenium WebDriver API, we can query and interact with browser cookies with the help of following WebDriver’s built-in methods.

    Get Cookies: This statement is used to return the list of all Cookies stored in web browser.


    Get Cookies by name: This statement is used to return the specific cookie according to its name.


    Add Cookies: This statement is used to create and add the cookie.


    Delete Cookies: This statement is used to delete a specific cookie.


    Delete Cookies by name: This statement is used to delete a cookie according to its name.


    Delete All Cookies: This statement is used to delete all cookies.


    Example: Cookie handling in Selenium.

    We will use http://demo.avactis.com for our demo purpose.

    This will be a 2 step process.

    • Step 1) Login into application and store the authentication cookie generated.
    • Step 2) Used the stored cookie, to again login into application without using userid and password.

    Step 1) Storing cookie information.

    import java.io.BufferedWriter; import java.io.File;
    import java.io.FileWriter; import java.util.Set;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver; 
    import org.openqa.selenium.Cookie;
    public class cookieRead{
    public static void main(String[] args)
    WebDriver driver;
    driver=new ChromeDriver();
    // Input Email id and Password If you are already Register 
    // create file named Cookies to store Login Information
    File file = new File("Cookies.data");
    // Delete old file if exists file.delete();
    FileWriter fileWrite = new FileWriter(file); 
    BufferedWriter Bwrite = new BufferedWriter(fileWrite);
    // loop for getting the cookie information
    // loop for getting the cookie information for(Cookie ck : 
    Bwrite.close(); fileWrite.close();
    catch(Exception ex)
    Using stored cookie to login into the application.

    Now, we will access the cookie generated in step 1 and use the cookie generated to authenticate our session in the application

    import java.io.BufferedReader; import java.io.File;
    import java.io.FileReader; import java.util.Date;
    import java.util.StringTokenizer; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    public class CookieWrite
    public static void main(String[] args){ 
    WebDriver driver;
    driver=new ChromeDriver(); 
    File file = new File("Cookies.data"); 
    FileReader fileReader = new FileReader(file);
    BufferedReader Buffreader = new BufferedReader(fileReader);
    String strline; 
    StringTokenizer token = new StringTokenizer(strline,";"); 
    String name = token.nextToken(); 
    String value = token.nextToken(); 
    String domain = token.nextToken(); 
    String path = token.nextToken(); 
    Date expiry = null;
    String val; 
    expiry = new Date(val);
    Boolean isSecure = new Boolean(token.nextToken()).
    Cookie ck = new
    // This will add the stored cookie to your current session
    }catch(Exception ex){ 

    OUTPUT: You are taken directly to the login success screen without entering the input user id and password

    Hash Testing Using Selenium

    HashMap is a interface in java and can implements various classes in java like Hashmap, Hashtable & many other. They are the part of collections framework and are used to handle. store data. Map interface represent the mapping in between key and value. What that mean it, in Map or hashmap, value is stored in the form of Key & Value pair. In this article i will try to demonstrate the same.

    We can use HashMap to with TestNG Dataprovider in Data Driven Testing. It can be Hash testing as we are using HashMap tp test data in selenium.

    Here, we read the data from the excel/csv file using Hashmap. Please go through below code example to read data from the external source using hashmap/dictionary or data driven approach.

    import java.io.File;
    import java.io.IOException; 
    import java.util.HashMap; 
    import jxl.Cell;
    import jxl.Sheet; 
    import jxl.Workbook;
    import jxl.read.biff.BiffException;
    class testclass {
    static String[][] getexceldatainArray; 
    static HashMap<String, String> dictionary;
    public static void main(String[] args) 
    throws IOException, BiffException {
    // Create an array based on data in excel file excelarrayclass tc = new excelarrayclass();
    getexceldatainArray = tc.CreateArrayfromExcel("D:\\Testing.xls",
    for (int i = 0; i < getexceldatainArray.length; i++) {
    dictionary = DataDictionaryFromArray(getexceldatainArray, i);
    // the keys will be value in the header column String username = dictionary.get("UserName");
    * Perform the required operation using the dictionary values
    System.out.println("UserName " + username);
    public String[][] 
    CreateArrayfromExcel(String WorkbookName, String SheetName)
    throws BiffException, IOException { 
    String[][] arrTestDta;
    Workbook workbk = Workbook.getWorkbook(new File(WorkbookName));
    Sheet wrkSheet = workbk.getSheet(SheetName);
    arrTestDta = new 
    // Loop to get data from excel file into an array
    for (int i = 0; i < wrkSheet.getRows(); i++) {  
    for (int j = 0; j < wrkSheet.getColumns(); 
    j++) {
    Cell cell = wrkSheet.getCell(j, i); 
    if (cell.getContents() != null) {
    arrTestDta[i][j] = cell.getContents();
    return arrTestDta;
    public static HashMap<String, String> DataDictionaryFromArray(
    String[][] arrayforDictionary, int iRow) {
    // Create a hashmap to store the data as dictionary in key value form
    HashMap<String, String> dictionary = new HashMap<String, String>();
    // get the size of the array, assuming being used in data driven test,
    // get the number of columns in the data 
    file int iColCnt = arrayforDictionary[0].length; 
    for (int i = 0; i < iColCnt; i++) {
    // mark the header column values as key and current column value as
    // key value pair 
    return dictionary;
    Screenshot Capturing

    While running the automation test suites using Selenium WebDriver, if defects are found then they are momentary and does not explain much of the details. In such case, it is desirable to take the screenshot which will capture all of the details of the defect. This helps the developer in bug analysis. Selenium WebDriver can take screenshots automatically with the help of
    class TakesScreenshot that is present in Selenium WebDriver API. In a similar way, we can generate PDF files as well.

    Following is the demonstration of a test script in Java to take test screenshot of a website using WebDriver API.

    Explanation of the test script

    In the test script, the first and foremost step is to instantiate the Firefox WebDriver. After instantiation, such an object has the reference as ‘driver’. With the help of this driver, object invoke and load the website URL. Here the URL under test is https://www.softwaretestingclass.com/. Here a method TakesSnapShot has created in the same class that accepts two arguments WebDriver instance and file path.

    Inside this method, web driver object is converting to TakesScreenshot with the following statement.

    TakesScreenshot screenShot = ((TakesScreenshot)webdriver);

    We are using the getScreenshotAs method of converted driver object in the last step. This accepts a single argument which is given as type FILE as shown below. It returns a file object.

    File SourceFile=screenShot.getScreenshotAs(OutputType.FILE);

    In the next step, we are instantiating a file that accepts the local file path (here
    c://selenium_demo//screenshot.png”). This file object we are passing as an argument along with the file object returned in the last step to copy the screenshot file as shown below.

    File DestinationFile=new File(fileLocalPath); FileUtils.copyFile(SourceFile, DestinationFile);


    When the above test script will run, it will capture a full screenshot of the website home page located at URL https://www.softwaretestingclass.com/ and will copy that screenshot PNG file to local drive (Path as“ c://selenium_demo//screenshot.png”). Shown below is the captured screenshot.

    Screen Reading Through Selenium

    Screen reading is also known as accessibility assessment automation. Accessibility assessment automation is a piece of code that can evaluate the web controls on a web page for accessibility. Accessibility assessment automation tools are useful because they can save a significant amount of time. The larger the site or the more complex the layout, the higher the chance of missing errors by manual testing. So accessibility automation can be used as an excellent way to generate a list of accessibility issues. There are various errors that can be caught by automation tools and do not need human inspection. A good example is in a case where images do not have any alt text, an accessibility assessment is an efficient way to document each instance one by one when an automatic means of finding is available.

    Tools used in accessibility accessment automation
    • Selenium-WEBDRIVER

      Selenium is a popular open-source web-based automation tool. It provides a more stable approach to automating the browser. More about Selenium can be found on the Selenium website: http://docs.seleniumhq.org/docs/03_webdriver.jsp. We used Selenium WebDriver to login to the application and to invoke the HTML_Code Sniffer on Web Page.

    • Testing Framework

      TestNG is a testing framework that is used with Selenium WebDriver. We used the TestNG framework for different types of annotations and to generate various type of reports (e.g. test output report)

    • Java

      Java is used as a scripting language. It is used with Selenium WebDriver to login to the application and inspect the web controls on the web page.

    • Eclipse

      We used Eclipse IDE (an editor) to write the code using the scripting language Java.

    • HTML Codesniffer

      The backbone of our accessibility assessment automation process. You can simply drag it from ‘http://squizlabs.github.io/HTML_CodeSniffer/’ and it will be added to your Bookmark. HTML_CodeSniffer is a client-side JavaScript that can check HTML code and detect WCAG 2.0 A/AA/AAA or Section 508 violations. For more information, please visit HTML_CodeSniffer. We did not invoke it from the bookmark; instead, we called the HTML Code_Sniffer JavaScript in Selenium code.

    Highlighting Elements through JavaScript in Selenium

    In Selenium, we can use JavascriptExecutor (interface) to execute Javascript code into webdriver.

    Here, we will execute Javascript which will highlight the element Let’s implement the same this will highlight the user name field.

    import org.openqa.selenium.By;
    import org.openqa.selenium.JavascriptExecutor; 
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    public class Highlight {
    public static void main(String []args){
    WebDriver driver=new FirefoxDriver();
    // Create the	JavascriptExecutor object 
    JavascriptExecutor js=(JavascriptExecutor)driver;
    // find element using id attribute
    WebElement username= driver.findElement(By.id("email"));
    // call the executeScript method 
    solid 2px red'');", username);

    In above program it, will highlight username field. Now we can not write every time the same code to highlight element so we will create reuse method and when we have to highlight element we will call the method.

    Create highlight element method for reuse
    public static void highLightElement(WebDriver driver, WebElement element)
    JavascriptExecutor js=(JavascriptExecutor)driver;
    js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", element);
    catch (InterruptedException e) {
    js.executeScript("arguments[0].setAttribute('style','border: solid 2px white');", element);
    Katalon Studio

    Katalon Studio is a free automation testing solution developed by Katalon LLC. The software is built on top of open-source automation frameworks Selenium, Appium with a specialized IDE interface for API, Web and Mobile testing .

    Katalon Studio is a comprehensive toolset for web and mobile app automation testing. This tool includes a full package of powerful features that help overcome common challenges in web UI test automation, for example, pop-up, iFrame, and wait-time. This user-friendly and versatile solution help tester test better, work faster, and launch high quality software thank to the intelligence it provides to the entire test automation process.

    • The test automation framework provided within Katalon Studio was developed with the keyword-driven approach as the primary test authoring method with data-driven functionality for test execution.
    • The user interface is a complete integrated development environment (IDE) implemented on Eclipse rich client platform (RCP).
    • The keyword libraries are a composition of common actions for web, API, and mobile testings. External libraries written in Java can be imported into a project to be used as native functions.
    • The main scripting language is Groovy, Java, and JavaScript and can be executed against all modern browsers, iOS, and Android applications supported by Selenium and Appium.
    • Katalon Studio monthly release includes the up-to-date open-source drivers matching the latest web and mobile environments to reduce the project maintenance cost and configuration efforts.
    • Cookie is a text file present in the web browser of the client machine or PC that stores a small piece of information
    • HashMap is a interface used in Hash testing.
    • Selenium WebDriver can take screenshots automatically with the help of class TakesScreenshot that is present in Selenium WebDriver API
    • Screen reading automation is a piece of code that can evaluate the web controls on a web page for accessibility.
    • JavascriptExecutor interface can be used to execute Javascript code into webdriver and to highlight element.
    • Katalon Studio is a comprehensive toolset for web and mobile app automation testing.

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.