Loading...

Follow LambdaTest Blog on Feedspot

Continue with Google
Continue with Facebook
or

Valid

Google Chrome, is without a doubt, the most popular browser in the world. In terms of user share, Google Chrome is well ahead of other major browsers like Mozilla Firefox, Safari, Opera, Microsoft Edge, etc. You can check how other browsers would fare in comparison to Chrome in our blog on the most important browsers for cross browser testing. In just over 10 years, Google Chrome has managed to conquer well over 65% of the market share. One of the key factors behind its meteoric rise is its huge library of extensions that truly sets it apart from the rest, especially for web designers and developers. However, offering a library of extensions as vast as it does, it becomes a bit troublesome for its users to handpick the extensions for their daily needs.

Being a web developer myself, I realize the complete ruckus involved in selecting an extension that could boost my daily basis productivity. It has happened so often that my colleagues refer me some new Chrome extension or two that has drastically helped me deliver better website faster. Looking back I realize, that I have been missing out on these essential Chrome extensions for web developers for months until I was notified by a co-worker. Many times I have helped my colleagues too & I am sure they must be feeling the same way as I did. It is a part of being human when you get to know about something that could have helped you do things faster, you end up saying “If only I knew about it earlier”.

In this article, I am going to highlight meticulously crafted 19 Best Chrome extensions for web developers & designers to boost their productivity and make their lives easier.

1. ColorZilla – Color Picker and Generator

ColorZilla is one of the oldest color picker extension launched over 8 years ago and it has successfully maintained its mantle as the best color picker and an eyedropper Chrome extension for developers or designers even today. ColorZilla will enable you to get a color reading from any pixel on the browser on the fly and paste it in any other program in RGB HEX formats. Just like Site Palette, ColorZilla also enables you to generate gradient colors and extract color palettes from any website. The extension also maintains a color history index of recently color picks.

2. Site Palette – Color Palette Generator

The next time you come across a website with a beautiful and pleasing color combination, this ingenious plugin can help you quickly extract and generate color pallets. It also allows you to download preview palette images, PDFs and generate shareable links. Site Palette is armed with seamless integration with coolers.co and Google Art Pallete. It has been an essential Chrome extension for developers & designers, throughout the globe.

3. Font Face Ninja – Font Identifier

Instead of inspecting elements in Chrome dev tools to find out the name of fonts being used, developers can instead rely on this elegant extension called Font Face Ninja to easily identify all the fonts being used on a webpage. Font Face Ninja boasts over 280k downloads and is the direct rival to another popular font face extension called WhatFont. To use this handmade Chrome extension for developers & designers, you simply have to hover over any text element on the webpage that you need to identify. A popup up floating window will display the name of the font face along with a small preview window for you to play around. You can bookmark your favorite font faces and save them for later use.

4. Marmoset – Code Snapshot Generator

Web designers and developers may encounter the need to create snapshots for their codes in their projects for aesthetics or representation purpose. Marmoset is a brilliant Chrome extension that allows you to create beautiful code snapshots in seconds with a single click. This might come in handy for social media posts or Portfolio website designs. It is one of the must-have Chrome extension for web developers & designers.

5. LambdaTest Screenshots – Cross Browser Testing Extension

As a developer, I have often noticed fellow developers missing out on testing what they have built. Sometimes, that careless attitude brings shame to the product, outages bringing discomfort in your office environment. And you feel silly once you get to the root cause of it, and realize that the web application wasn’t working as well for just one browser. This could be due to a deprecated CSS feature, or any other web element that is not so well supported by a browser.

I won’t blame developers for missing out on cross browser testing, as it isn’t feasible when you look at it. Installing multiple browsers, devices, through VMware or any other setup is a hassle for all. This is where LambdaTest comes in handy. LambdaTest provides a cloud-based platform to perform cross browser testing on 2000+ real browsers and browser versions for different devices, so you could end up with an eye-appealing, robust, and cross browser compatible website. For desktop devices, you get to test on both Windows and macOS. For mobile devices, you get to test on both android & iOS.

PERFORM CROSS BROWSER TESTING

SELENIUM GRID 2000+ Browsers

FREE SIGNUP

LambdaTest came up with a Chrome extension to help a user perform automated screenshot testing in bulk. The best part? You can perform screenshot testing across 25 devices in a single go. If you found any UI anomaly then you can share it with your colleagues on your preferred project management tool. Empowering you to perform cross browser testing in a jiffy, LambdaTest Screenshot is certainly one of the best Chrome extensions for developers, designers, and obviously testers, across the world. Here is a quick video to help you understand how simplistic the process is:

LambdaTest Chrome Extension For Automated Screenshots - YouTube

6. Page Ruler – Dimension and Size Checker

Page Ruler is one of the most essential and helpful Chrome extension for developers and designers on the list that helps web developers to quickly measure pixel perfect dimensions and positioning of any element on the page. This extension draws out a ruler image on the screen which allows you to inspect individual elements and view their dimension readings – width height along with positioning.

7. Dimensions – Dimension and Size Checker

Another key extension under this category is called Dimensions which helps to measure distances between various elements on a webpage. Its functioning is slightly different from Page Ruler. Dimensions measures distances from mouse pointer up/down and left/right until it reaches a border. This makes it the perfect tool to measure distances between images, input-fields, buttons, videos, gifs, text, icons. Another feature that sets Dimensions apart is its ability to work with mockups as well. If your designer has handed you Page design mockups in Jpeg or PNG formats, drop them inside Chrome and dimensions will work without a hitch. One thing that needs to be noted about dimensions is that it might not always work consistently well with images

8. Check My Links – Broken Link Checker

Check My Links is arguably the most powerful and robust broken link checker Chrome extensions for developers and designers in Chrome library. Check My Links crawls through the entire webpage and validates each individual link and reports whether it is valid or not. Check My Links empowers you to copy every broken link to your clipboard, in only a single click. Identifying and correcting Broken links is critical for any website for effective On-Page SEO and avoiding penalties from Google Site crawlers.

9. Clear Cache

Clear Cache extension helps to wipe clean your Cache along with browsing data with a single click without wasting time with any popups, dialogue windows or Chrome setting window. Furthermore, you can even customize how much data you want to clear on the extension option settings – App Cache, Cache, Cookies, Downloads, File Systems, Form Data, History, Indexed DB, Local Storage, Plugin Data, Passwords, and WebSQL. You can either delete cookies globally or for specific domains. One of the handiest Chrome extension for developers, designers, and everyone else too.

10. Wappalyzer – Site Analyser(Technology Identifier)

One of the biggest hurdles that developers face when coming across an impressive website face is the intriguing question – Which technologies have been used to make this website? This is where Wappalyzer comes to the rescue. This amazing extension is a cross-platform tool created by Elbert Alias in 2009 that uncovers the names of technologies used to create a particular website. It automatically detects over 1000 technologies like site generators, frameworks, libraries, plugins, CMS, databases, server software, widgets, analytics tools, etc. You can either use the Wappalyzer website or use the extension for quick usage. This Chrome extension for developers and designers has been a true lifeline for making appealing websites.

11. Ghostery – Privacy Tool

Ghostery is a privacy extension with built-in ad blocker to eliminate annoying advertisements from a website, tracking protection to protect your data and block 3rd party website from tracking along with page speed booster and optimizer to make your browsing experience uncluttered and pleasant. It also ships with a custom insights dashboard which you can customize to view relevant information.

12. JSON Viewer – JSON Beautifier And Viewer

If you are working extensively with APIs especially RestFul APIs or anything which involves a ton of JSON data, this visually stunning JSON highlighter serves great purpose as a Chrome extension for developers. Instead of viewing huge JSON file data in a clumsy unreadable format in your browser, JSON viewer helps to arrange JSON data in a visually appealing tree format which can view directly in your browser window.

13. Window Resizer – Screen Size Mockup

This extension is a lifesaver for responsive design coding. Although most developers are satisfied with default Chrome dev tools resizer feature, this Chrome extension for developers & designers can simulate any screen size and resolution of all popular devices like iPhones, iPad mac etc. This is quite helpful for developers to test out their layouts on different screen size devices and validate if their responsive media queries coding is working as intended or not.

Keep in mind though, Window Resizer would only be resizing the viewport to provide you with a near about idea of how your website will render on different screen sizes. For a more accurate and thorough responsive testing, you would need real mobile browsers to validate your website rendering.

Other than cross browser testing, LambdaTest also provides responsive testing where you get to visualize your website or web app on real mobile browsers. You can test across 46 mobile devices, both iOS & android, in a single test session.

14. Corporate Ipsum – Lorem Ipsum Generator

Another one of the most useful Chrome extensions for developers and designers. Instead of using the plain old standard lorem ipsum generators for creating placeholder text in your web layouts, why not try out using this smart tool that generates smart text rather than gibberish content. Corporate Ipsum extension is a special kind of lorem ipsum generator which creates mock business content text. This would make your layouts more visually appealing and presentable to clients.

15. Sessions Buddy – Tab/Session Manager

Google Chrome is infamous around the world for its massive appetite for RAM usage and developers with slower systems would constantly face screen freezes and crashes when working with multiple tabs. This is why effective tab management is indispensable especially when you lose the track of tabs you have opened looking for design inspiration or hashing out a solution on StackOverflow. The perfect tool for this mammoth problem is Sessions Buddy! Sessions Buddy is the most powerful Chrome extension for developers & designers to help them with browser tabs management. It also offers a bookmark manager with a simple and beautiful interface. It helps you to save sessions and restore them later when you open them on the fly. Therefore, avoiding clutter and keeping memory free. It allows you to manage all tabs in one page, organize them by topic and also offers quick search to look for a specific tab. Also, you need not worry about losing your session if you accidentally close your browser window or your system suffers a crash. Sessions Buddy will restore all your tabs as you left them.

16. CSS Viewer – CSS Property Viewer

Instead of wasting time looking for CSS properties of an element in the inspector window or the source code, CSS Viewer extension extracts all the valuable CSS properties and shows them in an organized manner inside a floating window. Simply hover over any element on the web page you want to inspect and the CSS viewer floating window will list out all the key CSS properties under categories – 1. Font and Text (font-family, font-size, font-weight, line-height, text-decoration, text-align), 2. Color and Background (color, background-color, background-position), 3. Box Model Properties (height, width, padding, margin), 4. Positioning, 5. Effects (transforms and transitions) and finally 6. Miscellaneous properties.

17. EditThisCookie – Cookie Manager

EditThisCookie is the most popular cookie manager extension in the Chrome Library with over 2.7million users which makes it the undisputed king when it comes to cookies. This tool allows you to add, delete, search, edit, block, and protect(Read-Only)cookies. Additionally, you can also import cookies in JSON or cookies.txt formats as well. This Chrome extension has been one of the most useful Chrome extension for developers & designers.

18. Checkbot – Site Auditor (SEO/Page Speed/Security)

Checkbot is an award-winning site-auditor extension that allows you to check over 250 URLs per site simultaneously to check SEO/Web Speed/Security issues like broken links, redirects, invalid HTML/CSS/JS, insecure password form, minify files, duplicate content etc. Checkbot runs tests based on 50+ best SEO and security practices based on recommendations from Google, Mozilla, and W3C. Using the Checkbot extension will help you craft perfectly optimized and secure websites which would slay Google SERP rankings. SERP ranking is crucial to every business on the internet, as a developer, you aim to provide a beautiful website but what good would that be if it wouldn’t have proper attention that it deserves?

I like to frequently run audits on my websites using Checkbot & find it a very convenient Chrome extension for developers and designers, around the globe.

19. Web Developer – Web Development Tools Package

An indispensable Chrome extension for developers and designers, this extension adds a toolbar with a complete suite of web development in your browser. The tools offered by this extension are divided into 10 separate tabs – Disable, Cookies, CSS,..

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Automation testing with Selenium has been a lifeline in grooming budding automation testers into professionals. Selenium being open-source is largely adopted on a global scale. As a result of which you get huge support from the community. There are multiple frameworks for different languages that offer bindings with Selenium. So you have got everything on board for getting started with Selenium. Now, comes the phases where you run your first test script to perform automation testing with Selenium. The scripts would involve basic test scenarios if you are learning Selenium automation. You may validate:

There could be many more things, one may look to validate as one aims to perform automation testing with Selenium. Today, I am going to help you perform one of the basic and fundamental validations for test automation with Selenium. I will demonstrate how you can handle multiple browser tabs using Selenium automation testing.

Getting Started With A Practical Scenario

Sometimes you may come across a complex scenario where you may have to open a new tab or window and perform desired actions on the opened tab/window. Handling multiple tabs or windows may seem complex at the start but once you know how to handle them, it becomes really easy. Let’s take into account a scenario.

Assuming, you open the homepage of Airbnb and wish to open the details of a homestay in another tab, perform some actions on the opened tab and then switch back to the previous tab. Then how do you do so?

You may find multiple solutions on the web regarding this. Few people use sendkeys method ‘Control + t’ to open a tab, post locating the body of the homepage. This approach most of the time does not work owing to sendKeys issue with the browser behavior. Hence, the best approach to open tab is using a Robot class or using JavascriptExecutor. Robot class ensure your tab is opened using the ‘Control + t’ command, while through javascript executor you can simply open the tab using windows.open. Post opening the tab you can switch to the tab using either Action Class approach or using Selenium WebDriver interface methods getWindowHandle & getWindowHandles. I will be showcasing both the approaches in this article.

The below test steps need to be addressed in order to open a tab in Airbnb.

  1. Open Airbnb URL.
  2. Search for ‘Goa’ location.
  3. Store URL of any stay.
  4. Open a new tab
  5. Switch to the new tab and launch the desired stored URL.

In order to open a new tab, the following Robot class code can be used:

Robot r = new Robot();        
        r.keyPress(KeyEvent.VK_CONTROL);
        r.keyPress(KeyEvent.VK_T);
        r.keyRelease(KeyEvent.VK_CONTROL);
        r.keyRelease(KeyEvent.VK_T);

The above code helps to open a tab using ‘control + t’ command of the keyboard. This can be performed using sendKeys but its credibility towards working or not seems sporadic owing to the behavior of the browser with which it is used. You can use sendKeys command as below to replicate the above behavior.

driver.findElement(By.cssSelector(“body”)).sendKeys(Keys.CONTROL+ “t”);

Handling Tabs In Selenium Using The Window Handler Method

Now, all we need to do is switch to this opened tab using Window Handler methods. Code snippet below for your reference:

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class HandlingMultipleTabs {

    public static void main(String[] args) throws InterruptedException, AWTException {
        // TODO Auto-generated method stub
        
        System.setProperty("webdriver.chrome.driver", ".\\ChromeDriver\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        
        //Navigating to airbnb
        driver.get("https://www.airbnb.co.in/");
        
        driver.manage().window().maximize();
        
        String currentHandle= driver.getWindowHandle();
        
        //locating the location, looking for homestays
        driver.findElement(By.id("Koan-magic-carpet-koan-search-bar__input")).sendKeys("Goa", Keys.ENTER);
        
        //Clicking on search button
        driver.findElement(By.xpath("//button[@type='submit']")).click();
        String urlToClick=driver.findElement(By.xpath("//div[text()='Luxury Three Bedroom Apartment with Pool & Jacuzzi']/ancestor::a")).getAttribute("href");
        
        //opening the new tab
        Robot r = new Robot();        
        r.keyPress(KeyEvent.VK_CONTROL);
        r.keyPress(KeyEvent.VK_T);
        r.keyRelease(KeyEvent.VK_CONTROL);
        r.keyRelease(KeyEvent.VK_T);
        
        //getting all the handles currently available
        Set<String> handles=driver.getWindowHandles();
        for(String actual: handles)
        {
            
         if(!actual.equalsIgnoreCase(currentHandle))
         {
             //switching to the opened tab
             driver.switchTo().window(actual);
             
             //opening the URL saved.
             driver.get(urlToClick);
         }
        }
        
        
        
    }
}

Use the below command if you wish to switch back to the original tab.

driver.switchTo().defaultContent();

Now, let’s try to open the tab using JavascriptExecutor and switch to that tab for the same scenario above. Below is the referenced code snippet:

import java.util.Set;
import java.util.concurrent.TimeUnit;

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

public class multipltabsonce123 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", ".\\ChromeDriver\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        
        //Navigating to airbnb
        driver.get("https://www.airbnb.co.in/");
        
        driver.manage().window().maximize();
        
        String currentHandle= driver.getWindowHandle();
        
        //locating the location, looking for homestays
        driver.findElement(By.id("Koan-magic-carpet-koan-search-bar__input")).sendKeys("Goa", Keys.ENTER);
        
        //Clicking on search button
        driver.findElement(By.xpath("//button[@type='submit']")).click();
        String urlToClick=driver.findElement(By.xpath("//div[text()='Luxury Three Bedroom Apartment with Pool & Jacuzzi']/ancestor::a")).getAttribute("href");
        
        //opening the new tab
        ((JavascriptExecutor)driver).executeScript("window.open()");
        
        //getting all the handles currently avaialbe
        Set<String> handles=driver.getWindowHandles();
        for(String actual: handles)
        {
            
         if(!actual.equalsIgnoreCase(currentHandle))
         {
             //switching to the opened tab
             driver.switchTo().window(actual);
             
             //opening the URL saved.
             driver.get(urlToClick);
         }
        }
        
    }

}

Kudos! You have successfully performed automation testing with Selenium for switching different browser tabs with the help of Windows Handler method. Now, let us go about it in a different manner.

Handling Tabs In Selenium Using The Action Class

As mentioned above, we can switch to tabs using both Window Handler and Action Class. The below code snippet showcases how to switch to tabs using Action class. Since action class also use inference of sendkeys, it may or may not work subjected to the browser under use.

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class HandlingMultipleTabs {

    public static void main(String[] args) throws InterruptedException, AWTException {
        // TODO Auto-generated method stub
        
        System.setProperty("webdriver.chrome.driver", ".\\ChromeDriver\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        
        //Navigating to airbnb
        driver.get("https://www.airbnb.co.in/");
        
        driver.manage().window().maximize();
        
        String currentHandle= driver.getWindowHandle();
        
        //locating the location, looking for homestays
        driver.findElement(By.id("Koan-magic-carpet-koan-search-bar__input")).sendKeys("Goa", Keys.ENTER);
        
        //Clicking on search button
        driver.findElement(By.xpath("//button[@type='submit']")).click();
        String urlToClick=driver.findElement(By.xpath("//div[text()='Luxury Three Bedroom Apartment with Pool & Jacuzzi']/ancestor::a")).getAttribute("href");
        
        //opening the new tab
        Robot r = new Robot();        
        r.keyPress(KeyEvent.VK_CONTROL);
        r.keyPress(KeyEvent.VK_T);
        r.keyRelease(KeyEvent.VK_CONTROL);
        r.keyRelease(KeyEvent.VK_T);
        
        
        
       //switch using actions class
        Actions action= new Actions(driver);
        action.keyDown(Keys.CONTROL).sendKeys(Keys.TAB).build().perform();
       
        //opening the URL saved.
        driver.get(urlToClick);
        
        
    }

}

And that is it! You have handled multiple browser tabs with Selenium automation testing using both Windows Handler method & using the Action Class as well. Now, I will be talking about one of the most common drawbacks of using Selenium. So we know that Selenium WebDriver is a great open-source tool for automating web applications. However, the primary pain point with WebDriver is the sequential execution of test scripts.

As a resolution, ThoughtWorks(Founder of Selenium) came up with Selenium Grid to help users run multiple test cases, simultaneously, in parallel. This drastically brought down the test builds execution.

So we have a way to run multiple test cases in parallel as we perform automation testing with Selenium. But how scalable is it?

Setting up a Selenium Grid of your own would demand a lot of CPU consumption & maintaining it comes as a hassle. The number of tests you wish to perform parallel execution with Selenium, the higher is the demand for computation. So what can you do? How can you perform automation testing with Selenium, at scale?

Executing Automation Testing With Selenium On Cloud

A cloud-based Selenium Grid will allow you to run your test cases without the hassle of infrastructure set up. All you would require is an internet connection. We have multiple platforms that help us provide a rich bed of browsers, versions, mobile devices, android versions etc.

Moving to cloud-based Selenium testing tool such as LambdaTest will help you scale effortlessly as you perform automation testing with Selenium.

Let us execute the above-demonstrated test cases on LambdaTest Selenium Grid. I will be showcasing how we can open multiple tabs, on a cloud-based platform and access the required details like video, screenshots, console logs, etc. for LambdaTest.

All you need to do is set up the LambdaTest URL while instantiating the remoteWebDriver. This URL is a combination of username, access key and LambdaTest hub URL. Now, all you need to do is define the platform, browser, version and the add-ons you require. Once this setup process is complete, use the same multiple tab script and run it on the LambdaTest platform. The referenced code snippet below:

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.net.URL;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class HandlingMultipleTabs {

    

    public RemoteWebDriver driver=null;
    public String url="https://www.lambdatest.com/";
    public static final String  username= "sadhvisingh24"; // Your LambdaTest Username
    public static final String auth_key = "abcdefghi123456789"; // Your LambdaTest Access Key
    public static final String URL= "@hub.lambdatest.com/wd/hub"; //This is the hub URL for LambdaTest
    
    
    @BeforeClass
    public void setUp()
    {
        DesiredCapabilities capabilities= new DesiredCapabilities();
        capabilities.setCapability("browserName", "chrome");
        capabilities.setCapability("version", "73.0");
        capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one
        capabilities.setCapability("build", "MultipleTabs_Lambdatest");
        capabilities.setCapability("name", "MultipleTabs_Lambdatest");
        capabilities.setCapability("network", true); // To enable network logs
        capabilities.setCapability("visual", true); // To enable step by step screenshot
        capabilities.setCapability("video", true); // To enable video recording
        capabilities.setCapability("console", true); // To capture console logs
        try {
             
         driver = new RemoteWebDriver(new URL("https://" + username + ":" + auth_key + URL), capabilities);
                
                } 
      
       catch (Exception e) {
                
           System.out.println("Invalid grid URL" + e.getMessage());
                }
    
        System.out.println("The setup process is completed");
    
    }
    
    
    @Test
    public void handleMultipleTabs() throws InterruptedException, AWTException {
        // TODO Auto-generated method stub
        
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        
        //Navigating to airbnb
        driver.get("https://www.lambdatest.com");
        
        driver.manage().window().maximize();
        
        String currentHandle= driver.getWindowHandle();
        
        //locating the blog url
        String urlToClick=driver.findElement(By.xpath("//a[text()='Blog']")).getAttribute("href");
        
        
        //opening the new tab
        ((JavascriptExecutor)driver).executeScript("window.open()");
        
        //getting all the handles currently availabe
        Set<String> handles=driver.getWindowHandles();
        for(String actual: handles)
        {
            
         if(!actual.equalsIgnoreCase(currentHandle))
         {
             //switching to the opened tab
             driver.switchTo().window(actual);
             
             //opening the URL saved.
             driver.get(urlToClick);
         }
        }
        
       
        
    }

    @AfterClass
    public void closeDown()
    {
        driver.quit();
    }
}

The above script will help you handle browser tabs in Selenium through an on-cloud Selenium Grid with zero-downtime. You can view the status of these test on the LambdaTest automation dashboard. You can view the video, screenshots, console output, and more as you perform automation testing with Selenium on LambdaTest. The referenced screenshot below:

Console Output of the test:

Conclusion

We demonstrated automation testing with Selenium to handle multiple tabs using both Action Class & Windows Handler method. We came to realize the pain point of running Selenium WebDriver, & Grid, locally. Moving to cloud-based Selenium Grid such as LambdaTest will help you scale effortlessly, so you could reduce your build times significantly & ship products faster.

Let me know in case you have any queries regarding this topic. I will be coming up with more articles around fundamental topics of Selenium automation testing, to help you grow better as a professional automation tester. Stay tuned for more & happy testing!

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Selenium is by far the most used web automation testing tools. One of the reasons behind this huge popularity is Selenium’s automated cross browser testing capabilities. Selenium automation testing can help you test on all major browsers, all major operating systems, and even on mobile device browsers. You can get a huge browser coverage in all your functional tests ensuring the perfect experience for a wide range of your potential users.

But there is a challenge. You can load only so many different browsers on your local machine. For example, if you have a windows machine, you cannot test on Safari browsers, similarly, if you have a Mac machine you won’t be able to test on IE or Edge browsers. In addition, running tests on a single machine was a time-consuming process. If you have multiple computers, why test on a single one at a time?

The ideal scenario would be to test on a network of interconnected machines having different browser environments running multiple tests cases concurrently, in parallel, and reducing the overall testing time by multiple folds. And here I am also including time taken for cross browser testing as well.

And that is exactly what Selenium Grid is built for. Unlike Selenium WebDriver which allows you to perform automated cross browser testing in a sequential manner, a Selenium Grid setup will allow you to run test cases in different browsers/ browser versions, simultaneously.

What Is Selenium Grid?

Before we start with Selenium Grid setup, it is necessary to realize the basics of a Selenium Grid.

So, the Selenium Grid basically allow us to run our automated tests on different operating systems against different browsers. And that too in a parallel manner. Selenium automation testing tool will help you with faster automated cross browser testing, along with efficient utilization of in-house hardware.

Selenium Grid is comprised of two concepts:

  • Hub: It is the center of the Selenium Grid setup architecture that manages the network of the test machines. There is only one hub in a network which is assigned to a test of DesiredCapabilities(operating system, browser, browser versions) and then the hub finds the test that matches the given configurations.
  • Node: Nodes are the test machines that execute the test that was earlier loaded on the hub. There can be multiple nodes configured with a different operating system and different browsers. It is not mandatory for the node to run on the same platform on which the hub is running.

Infrastructure to configuring a Selenium Grid setup for parallel execution involves just two steps:

  1. Creating a hub.
  2. Defining the nodes and connecting to that hub.
Using Command Prompt For Selenium Grid Setup

The first step of a Selenium Grid setup would be to create a hub. You would have to make sure that your system has Java Runtime Environment (JRE) or better yet Java Development Kit (JDK) installed. Though most people recommend going for the latest JDK, I prefer an earlier tried and tested versions like JDK SE 08 or 09. You can go for the latest one if you wish. Here are the next steps –

  • Download and extract Selenium Standalone server JAR files. You can download them from here.
  • Next, open a command prompt or terminal and navigate to the directory where the Selenium Standalone Server jar file is saved.
  • Run the command “java -jar selenium-server-standalone-3.141.59.jar -role hub”. This command would launch a Selenium Grid hub on port 4444 by default. You can also check the same by directing to http://localhost:4444/grid/console.

Since the hub has already been created, the next step to Selenium Grid setup for parallel execution would involve launching a node. You start with going to the other machines where we want to setup nodes. Again, these machines should have a JDK/JRE setup.

In the node machine, open a command prompt or terminal and navigate to the directory where you have saved the browser driver files.

Enter the below command in order to configure Chrome driver in your Selenium Grid setup for parallel execution.

“java -Dwebdriver.chrome.driver="C:\chromedriver.exe" -jar 
selenium-server-standalone-3.141.59.jar -role webdriver -hub 
http://10.0.0.22:4444/grid/register -port 4546”

  • In the above command I have used my machine IP along with the port 4444 where the hub is actually running. I have also selected the port 4546 where I want my node to get registered. You can opt for any free port for registering the node.

Similarly, you can register other nodes for other browsers. For example, here’s how you can configure Firefox(Gecko) driver and Internet Explorer driver to your Selenium Grid setup for parallel execution.

Configuring Firefox(Gecko) driver in Selenium Grid setup:

“java -Dwebdriver.gecko.driver="C:\geckodriver.exe" -jar 
selenium-server-standalone-3.141.59.jar -role webdriver -hub 
http://10.0.0.22:4444/grid/register -port 5566”

Configuring IE(Internet Explorer) driver in Selenium Grid setup:

“java -Dwebdriver.ie.driver="C:\IEDriverServer.exe" -jar 
selenium-server-standalone-3.141.59.jar -role webdriver -hub 
http://10.0.0.22:4444/grid/register -port 4547”

Note: Please make sure that you select different ports for different nodes to connect with the single hub running on port 4444. Also, before running your test on IE, make sure that the browser zoom is exactly 100% otherwise it might show an error.

You can notice by above commands that we are running our first node for chrome driver on port 4546, the second node for firefox driver is running on port 5566, and the third node for IE browser is running on port 4547. Here is the output screenshot for further reference:

Now, that we have our Selenium Grid setup configured, your next step is to perform Selenium automation testing for your cross browser testing suite.

Execute Automation Testing With Selenium Grid For Parallel Execution

It is time for some automated cross browser testing! I will be running an automation script demonstrating the Selenium Grid for parallel execution. This script would run parallelly on Chrome, Firefox, and Internet Explorer which are registered on different ports and attached to a single hub.

Here is the sample code I used to perform automation testing with Selenium Grid for parallel execution in different browsers.

package DemoAutomation;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;


public class Selenium_MultiBrowser_Test 
{
    WebDriver driver;
    String nodeURL;
    
    @Parameters({"Port"})
    @BeforeMethod()
    public void setUp(String Port) throws MalformedURLException
    {           
        if(Port.equalsIgnoreCase("4546"))
        {
            nodeURL = "http://10.0.0.22:4546/wd/hub";
            System.out.println("Chrome Browser Initiated");
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();            
            capabilities.setBrowserName("chrome");
            capabilities.setPlatform(Platform.WINDOWS);
            
            driver = new RemoteWebDriver(new URL(nodeURL),capabilities);
            
            driver.get("https://www.apple.com/");
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        }
        
        else
            if(Port.equalsIgnoreCase("5566"))
            {
                nodeURL = "http://10.0.0.22:5566/wd/hub";
                System.out.println("Firefox Browser Initiated");
                DesiredCapabilities capabilities1 = DesiredCapabilities.firefox();
                capabilities1.setBrowserName("firefox");
                capabilities1.setPlatform(Platform.WINDOWS);
                
                driver = new RemoteWebDriver(new URL(nodeURL),capabilities1);   
                
                driver.get("https://www.apple.com/");
                driver.manage().window().maximize();
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            }
        
        else
            
        if(Port.equalsIgnoreCase("4547"))
        {
            nodeURL = "http://10.0.0.22:4547/wd/hub";
            System.out.println("Internet Browser Initiated");
            DesiredCapabilities capabilities2 = DesiredCapabilities.internetExplorer();
            capabilities2.setBrowserName("internet explorer");
            capabilities2.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
            capabilities2.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
            capabilities2.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
            capabilities2.setCapability("ignoreProtectedModeSettings", true);
            capabilities2.setCapability("nativeEvents", false);
            capabilities2.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL, "");
            capabilities2.setCapability(InternetExplorerDriver.LOG_LEVEL, "DEBUG");
             
            
            capabilities2.setPlatform(Platform.WINDOWS);
            
            driver = new RemoteWebDriver(new URL(nodeURL),capabilities2);
            
            driver.get("https://www.apple.com/");
            driver.manage().window().maximize();    
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        }
    }
    
    @Test
    public void appleSite() throws InterruptedException
    {
        try
        {
        
        driver.findElement(By.xpath("//*[@id=\'ac-globalnav\']/div/ul[2]/li[3]")).click();
        Thread.sleep(2000);

        driver.findElement(By.cssSelector("#chapternav > div > ul > li.chapternav-item.chapternav-item-ipad-air > a > figure")).click();
        Thread.sleep(2000);

        driver.findElement(By.linkText("Why iPad")).click();
        Thread.sleep(2000);
        }
        
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }

    
    @AfterMethod()
    public void tearDown()
    {
            driver.quit();
            System.out.println("Browser Closed");
    }
}

Above is the java class file that is configured with the XML file which includes the values of parameters passed in the java file and also helps in creating a suite of different classes that would run in a parallel manner.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="3" name="BlogSuite" parallel="tests">

<test name="Chrome Test">
<parameter name="Port" value="4546"/>
    <classes>
      <class name="DemoAutomation.Selenium_MultiBrowser_Test"/>
      
    </classes>
  </test> 
  
  <test name="Firefox Test">
<parameter name="Port" value="5566"/>
    <classes>
      <class name="DemoAutomation.Selenium_MultiBrowser_Test"/>
      
    </classes>
  </test> 
  
  
  <test name="Internet Explorer Test">
<parameter name="Port" value="4547"/>
    <classes>
      <class name="DemoAutomation.Selenium_MultiBrowser_Test"/>
      
    </classes>
  </test> 
  
  
  </suite>

Output Screen:

In the above code, I have used DesiredCapabilities class that would help you set properties for the Selenium WebDriver. These properties can be used to configure instances of browser such as BrowserName and BrowserVersion on which you want your script to run on.

Note: However, the script would only run on the browser and browser version that is currently installed on the test machine. Suppose, if you try running your test on Chrome 72 and you only have Chrome 74 installed on your test machine, then your script would show an error. This same scenario occurs while you opt for the different operating system compared to the operating system of your test machines.

In addition, it is quite expensive to invest in new Mac and Windows environments every time a new OS is launched.

So, if you wish to perform automated cross browser testing on different browsers, browser versions and operating systems then I would recommend you to look for a tool that offers Selenium Grid setup on-cloud, such as LambdaTest.

LambdaTest saves you from the hassle of maintaining your Selenium Grid setup, so you could focus on writing better automation code. LambdaTest also empowers you with that ability of Selenium Grid for parallel execution, all on the cloud.

What Is LambdaTest?

LambdaTest is a cross browser testing platform on cloud. It’s an online manual and automated testing tool where you can test your website/ web application across 2000+ combinations of browsers, browser versions, and operating systems.

With LambdaTest, not only can you perform Selenium automation testing, you could even perform live interactive real time cross browser testing, responsive testing of your web app/ website as well.

Want to know the difference between Cross Browser Testing & Responsive Testing? Read our blog around it.

Running Automated Tests On LambdaTest Selenium Grid Cloud

Let’s try running our same test case on LambdaTest Selenium Grid. You can use LambdaTest Desired Capabilities Generator for configuring the desiredcapabilities object. This would save you a lot of your time spent in Selenium Grid setup when done manually.

With LambdaTest, you only need to create a Remote Server, add your LambdaTest username, access key, and the Grid URL in your script, and then you are good to go.

Below is the Java code in the TestNG framework that would be more beneficial in this scenario:

package lambdatest;
import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class SampleTest {
   public String username = "enteryourusernamehere";
  public String accesskey = "enteryourkeyhere";
  public RemoteWebDriver driver = null;
  public String gridURL = "@hub.lambdatest.com/wd/hub";
  boolean status = false;

  @BeforeTest
  @org.testng.annotations.Parameters(value={"browser","version","platform"})
  public void setUp(String browser, String version, String platform) throws Exception {
     DesiredCapabilities capabilities = new DesiredCapabilities();
      capabilities.setCapability("browserName", browser);
      capabilities.setCapability("version", version);
      capabilities.setCapability("platform", platform); // If this cap isn't specified, it will just get the any available one
      capabilities.setCapability("build", "Selenium Grid");
      capabilities.setCapability("name", "Sample Test");
      capabilities.setCapability("network", true); // To enable network logs
      capabilities.setCapability("visual", true); // To enable step by step screenshot
      capabilities.setCapability("video", true); // To enable video recording
      capabilities.setCapability("console", true); // To capture console logs
      try {
          driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
      } catch (MalformedURLException e) {
          System.out.println("Invalid grid URL");
      } catch (Exception e) {
          System.out.println(e.getMessage());
      }
  }

  @Test
  public void testSimple() throws Exception {
     try {
            
            driver.get("https://www.apple.com/");
            driver.manage().window().maximize();
            
            driver.findElement(By.xpath("//*[@id=\'ac-globalnav\']/div/ul[2]/li[3]")).click();
            Thread.sleep(2000);

            driver.findElement(
            By.cssSelector("#chapternav > div > ul > li.chapternav-item.chapternav-item-ipad-air > a")).click();
            Thread.sleep(2000);

            driver.findElement(By.linkText("Why iPad")).click();
            Thread.sleep(2000);
          
      } catch (Exception e) {
          System.out.println(e.getMessage());
      }
  }
  
 
  @AfterTest
  public void tearDown() throws Exception {
     if (driver != null) {
          ((JavascriptExecutor) driver).executeScript("lambda-status=" + status);
          driver.quit();
      }
  }
}

Now, we would run this Java class file with the XML file that contains the value of parameters passed in the Java file and also helps in creating a suite of different classes, using which, we can perform automation testing with Selenium Grid for parallel execution on different configurations.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="3" name="BlogSuite" parallel="tests">
 
  <test name="FirefoxTest">
  <parameter name="browser" value="firefox"/>
  <parameter name="version" value="62.0"/>
  <parameter name="platform" value="WIN8"/>
    <classes>
      <class name="lambdatest.SampleTest"/>
    </classes>
  </test> 
 
  <test name="ChromeTest">
  <parameter name="browser" value="chrome"/>
  <parameter name="version" value="70.0"/>
  <parameter name="platform" value="WIN10"/>
    <classes>
      <class name="lambdatest.SampleTest"/>
    </classes>
  </test> 

  <test name="SafariTest">
  <parameter name="browser" value="safari"/>
  <parameter name="version" value="11.0"/>
  <parameter name="platform" value="macos High Sierra"/>
    <classes>
      <class name="lambdatest.SampleTest"/>
    </classes>
  </test> 
 
</suite>

Output Screen:

Now, we have successfully executed automation testing with Selenium Grid for parallel execution on different browsers along with different operating systems without any hassle of creating a hub and launching the nodes on different ports. While the test is running on a Selenium Grid, you can see the live video streaming of your tests and various other details such as commands which includes the screenshot of each command passed by your script and also the logs and exceptions raised.

AUTOMATED CROSS BROWSER TESTING

SELENIUM GRID 2000+ Browsers

FREE SIGNUP

You can also create your own team and run your automated cross browser compatibility testing scripts as a team. These test results would be visible to each member added in a team. In addition through our single click integration, your teammates can log any bug found during their cross browser testing session directly to various project management platforms like Jira, Trello, Asana, Mantis, GitHub, etc. In addition, LambdaTest also integrates with CI/CD platforms that are complementary to your automation testing tools like CircleCI, Jenkins, TravisCI, etc. Check out all of the LambdaTest integrations.

Conclusion

Selenium Grid setup, if done manually, could be challenging. If the main purpose of Selenium Grid is to run tests in parallel and test on a different configuration, you can perform the same on LambdaTest without investing time and resources on creating Selenium Grid hub and Selenium Grid nodes. So, give it a try once by running your automated tests on this online Grid and let us know in the comment box about your feedback using LambdaTest. Happy Testing!

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

One of the most performed actions of any webpage tester is taking a screenshot of the webpage. Whenever a tester finds and reports a bug, that bug would not be taken seriously without supporting screenshots or even videos of the issue. This is equally true no matter the type of testing you are doing and that includes selenium automation testing.

In automation testing, especially where a typical test run may involve hundreds of commands and test cases, automated screenshots taken at critical assertions are important for developers and testers in making sure that every test case executed as it should. These proofs are in-turn used for debugging, to find out what went wrong and the reason for failure. For automation testing with selenium, these screenshots help to distinguish whether the failures are due to application failure or due to script failure.

Now with that said, when we say screenshot we could mean capturing an image of any part of the screen including the image of an element in question or even a screenshot of the whole page. Therefore in this post, we would be looking at how you can take automated screenshots of web pages for different purposes using Selenium WebDriver automation scripts. To start off, there are four major ways of capturing screenshot images using Selenium Webdriver. Such as :

  • Screenshot of Viewable area
  • Screenshot of entire screen i.e. capturing screenshot of full webpage
  • Screenshot of the desired webElement
  • Cloud based platform supporting screenshots of AUT
Automated Selenium Test Scripts for Taking Screenshots of Viewable Area

This is the most used approach of taking screenshots of applications under automation and the easiest one as well. Selenium provides an out-of-the-box capability called TakeScreenShot interface that can be used for taking screenshots of the viewable area.

You can check the detail of the interface here.

This interface provides a method known as getScreenshotAs which helps to capture the screenshot and store it in the desired location.

Here’s the syntax to capture the screenshot:

File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

In order to store the taken screenshot into a file, the below statement is used:
FileUtils.copyFile(screenshotFile, new File("path of the file you want to save the screenshot to"));

This is it! Just two statements and you will be able to take the screenshot. Let’s incorporate this step into a code snippet. The below example showcases Airbnb stay details page example where we are taking a screenshot of the viewable screen:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ViewableScreenshotExample {
    
    WebDriver driver;
    
    @BeforeTest
    public void setupUrl()
    {
        System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe");
        driver=new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://www.airbnb.co.in/s/India/");
        
        
    }
    
    @Test
    public void performAction() throws InterruptedException
    {
        //Scroll down the page
        JavascriptExecutor jse = (JavascriptExecutor)driver;
        jse.executeScript("window.scrollBy(0,250)", "");
        
        
        //open the stay details page
        driver.findElement(By.xpath("//div[contains(text(), 'Sea Hut Homestay with Aircon')]")).click();
        Thread.sleep(1500);
        
        //Switch to the required tab
        ArrayList<String> ta = new ArrayList<String> (driver.getWindowHandles());
        int i=ta.size();
        System.out.println(i);
        driver.switchTo().window(ta.get(1));
    }
    
    @AfterTest
    public void takeScreenshot()
    {
        //take screenshot of the page
        File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(src, new File("path of the file"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

The code snippet above will take the viewable screen screenshot as below:

This is all good and awesome if you have to take a screenshot of the view that your code is testing. However, if I want to take a screenshot of the entire webpage, the above mentioned code is not enough. But we have a solution.

Capturing Full Webpage Screenshot using Automated Selenium Test Scripts

A need may arise to take screenshots of the entire screen rather than just the viewport of the browsers. Some browsers take a screenshot of the viewable port only whereas others take a screenshot of the entire screen. Earlier versions of Firefox used to take screenshots of the entire screen, unlike chrome and IE. But eventually even the latest versions of Firefox now only takes viewport screenshots. So in order to capture screenshots of the entire screen using selenium web driver scripts, we can make use of AShot().

AShot() is a webdriver screenshot utility to capture entire page screenshot and is natively supported from Selenium 3 onwards. It provides the following features:

  1. Helps capture entire screen and web element
  2. Beautify screenshot
  3. Provides screenshot comparison.

For more details on the utility, you can refer here.

In order to take a screenshot of the entire screen, you need to add the jar into your project. You can download the jar from here http://central.maven.org/maven2/ru/yandex/qatools/ashot/ashot/1.5.3/ashot-1.5.3.jar

Once the jars are added into the project, all you need to do is mention the below lines of code when you intend to take the full-screen screenshot:

Screenshot screenshot=new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
ImageIO.write(screenshot.getImage(),"PNG",new File("path of the file"));

In the code below, the Ashot method shooting strategy is used by setting the viewport to full screen and taking screenshots. This code snippet below goes to Airbnb India Stays and Tours page and takes a screenshot of the full view.

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;

public class EntireScreenshot {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
    WebDriver driver;
        
        
                System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe");
            driver=new ChromeDriver();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            driver.manage().window().maximize();
            driver.get("https://www.airbnb.co.in/s/India/");
            
//take screenshot of the entire page
            Screenshot screenshot=new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
            try {
                ImageIO.write(screenshot.getImage(),"PNG",new File("path of the file"));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            driver.quit();
           
        }
                
    


    }

As you run this code, note how the code automatically scrolls down the page and takes the screenshot of the entire page. Below is the example of the taken screenshot.

Taking full pages screenshots is great, but you may encounter a use case where you are concerned with the screenshot of the desired webElement only. Your only concern will be to take a screenshot of the desired element and not the whole screen. Also, if you wish to take screenshots of the logo image or other UI specific element to check its pixilation or UI issues, all you care about is taking the webElement image rather than the whole screen image. Let dig into as how to take a screenshot of a web Element.

Taking Screenshot of Desired Web Element Using Selenium WebDriver

Taking screenshot of a desired element is also pretty easy. The main concept is to crop the full screenshot to the desired location of the webElement based on its coordinates and height-width. Here’s a code snippet below highlighting how you can take screenshot of just the logo of Amazon.com website.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.server.handler.FullscreenWindow;

public class LogoScreenShotExample {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        
        
        
    System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe");
    WebDriver driver=new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("https://www.amazon.in/");
    
    //locating amazon logo
    WebElement logo=driver.findElement(By.id("nav-logo"));
    
    // Get entire page screenshot
    File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    
    BufferedImage  fullScreen = ImageIO.read(screenshot);
    
    //Find location of the webelement logo on the page
    Point location= logo.getLocation();
    
    //Find width and height of the located element logo
    
    int width= logo.getSize().getWidth();
    int height=logo.getSize().getHeight();
    
    
    //Now the main point, which is cropping the full image to get only the logo screenshot
    BufferedImage logoImage= fullScreen.getSubimage(location.getX(), location.getY(),
            width, height);
    
    ImageIO.write(logoImage, "png", screenshot);
    
    //copy the file to the desired location
    FileUtils.copyFile(screenshot, new File("path of file"));
    

    }

}

Here’s the image was taken by the above code snippet of the webElement:

This is it. Isn’t it cool guys. Just find out what your test scenario wants and take the required screenshot. Nowadays we do not need to take screenshots because of so many upcoming cloud-based platforms providing support to all those screenshots and videos to your automation scripts execution.

This brings me to my last approach of taking a screenshot which eventually means not taking one and the tool doing its job. Well, you heard it right. Let’s look into its details

Taking Full Page Automated Screenshots On Cloud

Running tests locally is important however if you want to make sure that your website works on all browsers, even those you don’t have access to locally, you would need service like LambdaTest. LambdaTest is a cloud based selenium grid that you can use to run all your automated selenium test scripts online. The best part about LambdaTest grid, however, is that it takes automated screenshots of your webpage after the execution of each selenium command. In addition, LambdaTest platform takes a complete video of the test execution as well. All you need to do is run your scripts on this platform which provides you features like screenshots, videos, network logs, console logs and so on. Few points of consideration or pre-conditions to make your script running on the platform is:

  1. LambdaTest account
  2. LambdaTest Username, access key and URL to connect to
  3. Setting up the required properties to gain access to the features you need.

This is it. Now let’s run our same above-mentioned code of Airbnb Stays detail page without the need of providing the screenshot method since it captures the whole video of the execution. In the below code snippet I will be using LambdaTest username, access key, and LambdaTest Selenium Grid URL to connect to the required browser and perform actions. Notice that changing the above code into LambdaTest compatible code required only to call remote webdriver instead of local chrome webdriver, and passing on a desired-capabilities object to define which browser you need to run tests on.:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.net.URL;

public class LambdatestWithoutScreenShotMethod {


    
    public static final String  username= "sadhvisingh24";
    public static final String auth_key = "X1PLnv28q0eSqWoqaqv9STD4gPRfWnVOisEUcmlW0zg9HO3GYi";
    public RemoteWebDriver driver;
    public static final String URL= "@hub.lambdatest.com/wd/hub";
    
    @BeforeTest
    public void setupUrl()
    {
        
            DesiredCapabilities capability= new DesiredCapabilities();
            capability.setPlatform(Platform.WIN8);
            capability.setBrowserName("chrome");
            capability.setVersion("75.0");
            capability.setCapability("build", "cross_browser");
            capability.setCapability("name", "cross_browser");
            capability.setCapability("network", true);//to enable network logs
            capability.setCapability("visual", true);//to enable screenshots
            capability.setCapability("video", true);//to enable video
            capability.setCapability("console", true);//to enable console logs
                
             try {
                     
             driver = new RemoteWebDriver(new URL("https://" + username + ":" + auth_key + URL), capability);
                    
                 } 
       
           catch (Exception e) {
                    
               System.out.println("Invalid grid URL" + e.getMessage());
                 }
     
                 try
                {
                  driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
                    driver.manage().window().maximize();

                driver.get("https://www.airbnb.co.in/s/India/");

                   }
                catch (Exception e) {
             System.out.println(e.getMessage());
                    }
        }   
            
    
    @Test
    public void performAction() throws InterruptedException
    {
        //Scroll down the page
        JavascriptExecutor jse = (JavascriptExecutor)driver;
        jse.executeScript("window.scrollBy(0,250)", "");
        
        
        //open the stay details page
        driver.findElement(By.xpath("//div[contains(text(), 'Sea Hut Homestay with Aircon')]")).click();
        Thread.sleep(1500);
        
        //Switch to the required tab
        ArrayList<String> ta = new ArrayList<String> (driver.getWindowHandles());
        int i=ta.size();
        System.out.println(i);
        driver.switchTo().window(ta.get(1));
    }
    
    @AfterTest
    public void closeSetup()
    {
        driver.quit();
    }


}

The referenced screenshot below:

In the screenshot above, LambdaTest provides support of video where you can view the whole execution flow of your web app.

RUN SELENIUM SCRIPTS IN PARALLEL ON SELENIUM GRID

2000+ Browsers AND OS

FREE SIGNUP

Apart from this LambdaTest also provides a standalone full paged automated screenshot feature, that can help you to take screenshot across browsers of your designated application and even compare them. LambdaTest calls this feature as ‘Screenshot testing’. You can access these screenshots as and when required and even share them with the required stakeholders and mail them as per needs. This feature comes in handy when you got to test your application across multiple browsers and versions and perform cross browser testing. You can take screenshots and compare them for any UI issues. Isn’t it miraculous and just imagine the amount of time you just saved.

  1. Navigate to the LambdaTest ‘Visual UI testing’ menu header and navigate to its sub-header ‘Screenshot’ as below
  2. Once you reach this page, all you need to do is place the URL you intend to test in the URL placeholder. Select the required browser and version you wish to take a screenshot on and just click on the button ‘capture’. Bingo, that’s it.
  3. The images to be captured will be added in the queue. Once it’s completed, you can access those images, as below:

As you saw above, we focused on all possible ways of taking screenshots in detail, so next time when you are stuck on how to take a screenshot, this article will come in handy. You can also refer to my other articles as part of this series. Happy testing.

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Test automation with Selenium has empowered website testers over the globe to perform automated website testing with ease. Webdriver is a core component of the Selenium framework using which you can perform automated cross browser testing of your website or web application against different types of browsers e.g. Google Chrome, Mozilla Firefox, Safari, Opera, Internet Explorer, Microsoft Edge, etc.

The primary advantage of performing test automation with Selenium Webdriver over other web automation tools/frameworks is the support for a wide number of programming languages namely Python, Java, C#, Ruby, PHP, JavaScript, .Net, Perl, etc. If you are new to automation testing with Selenium WebDriver, then you can have a look at our Selenium WebDriver tutorial for automated cross browser testing where we talk about the overall architecture of Selenium and how the framework can be used with popular programming languages. You can also check my previous article on Selenium Grid setup Tutorial for cross browser testing, to leverage the ability of parallel testing with Selenium. Irrespective of the programming language being used, there are certain best practices that are applicable for performing test automation with Selenium Webdriver (independent of the development language).

In this article, I will share with you some key tips for Selenium automation testing, that touch upon aspects of code optimization, performance improvements, dynamic web-page loading, handling CSS and HTML code, etc.

Note – Majority of these coding tips for test automation with Selenium WebDriver are generic in nature and can be applied irrespective of the programming language used for the development of test scripts. However, for below demonstration, we have made use of Selenium with Python language.

Selenium Tip #1 – Setting The Executable Path Of The Selenium Webdriver

In order to communicate with the browser under test, you need to first download the corresponding plugin/webdriver from their official website. This plugin would be responsible for communicating with the browser and it should be present in your machine (on which you are developing the tests). The plugin/webdriver path has to be set in the Selenium Webdriver configuration.

Though the plugin/webdriver can be placed in any location since you can provide the static/relative path in the Selenium Webdriver configuration, the approach can be error prone and you need to keep track of the file path. A better & more reliable approach is to place the corresponding Selenium Webdriver in the location where the driver executable is present, in which case you need not specify the executable path in the Selenium Webdriver configuration.

If the geckodriver is not present in the Browser location, you need to manually add the path of the same in the source code. We import the selenium.webdriver.firefox.firefox_binary module to provide the path to the Firefox executable.

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

ff_binary = FirefoxBinary('path/to/gecko driver')
browser = webdriver.Firefox(firefox_binary=ff_binary)

As seen in the code snippet below, we have not specified the location of the geckodriver (Firefox Webdriver) since it is placed in the same location where Firefox browser is present. This is more reliable approach compared to the previous one and can help in reducing basic errors in implementation of test automation with Selenium.

''' Import the required modules for development '''
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep

'''Creation of Firefox Webdriver '''
driver = webdriver.Firefox()
driver.get("https://www.lambdatest.com/")

Selenium Tip #2 – Capture Screenshot Of Test Automation With Selenium WebDriver

While performing tests, you would have come across requirements where a screenshot has to be captured for verifying results of the tests. Selenium WebDriver offers three APIs through which you can take a screenshot of a web-page.

  1. save_screenshot(‘path-where-screenshot-should-be-saved/filename.png’)
  2. get_screenshot_as_file(‘path-where-screenshot-should-be-saved/filename.png’)
  3. get_screenshot_as_png()

The first two APIs lets you save the screen of the current window in a .png file. The API returns False if there is an IOError, else it returns True. These APIs would only work if the file extension is .png, else Python throws an error & the saved content might not be viewable. If you wish to capture a screen of your current window in a binary format then make use of get_screenshot_as_png() API.

''' Import the required modules for development '''
from selenium import webdriver
import StringIO
from PIL import Image

'''Creation of Firefox Webdriver '''
driver = webdriver.Firefox()
driver.get("https://www.lambdatest.com/")

'''Taking screenshot of the web-page. File would be saved in the location where the source code is present '''

'''Option - 1'''
driver.save_screenshot('screenshot_1.png');


'''Option - 2'''
driver.get_screenshot_as_file('screenshot_2.png');
'''Option - 3'''
screenshot = driver.get_screenshot_as_png();
    
screenshot_size = (20, 10, 480, 600)
image = Image.open (StringIO.StringIO(screen))
region = image.crop(screenshot_size)
region.save('screenshot_3.jpg', 'JPEG', optimize=True)

Selenium Tip #3 – Refreshing WebPage While Automation Testing With Selenium WebDriver

There might be scenarios where there is a requirement for refreshing a web page, especially while waiting for a specific condition. There are a number of ways through which a webpage can be refreshed while performing test automation with Selenium Webdriver, the popular one is listed below.

1. driver.refresh() method

As the name signifies, the refresh() method is used to refresh the web page. It is asynchronous in nature hence; you should make use of this API in conjunction with document.readyState().

''' Import the required modules for development '''
from selenium import webdriver

'''Creation of Firefox Webdriver '''
driver = webdriver.Firefox()
driver.get("https://www.lambdatest.com/")
driver.refresh()

2. ActionChains() method

ActionChains() are another way to automate low-level interactions for automation testing with Selenium, such as key press, mouse button actions, etc. In order to refresh the webpage, we make use of the ‘CTRL + F5’ combination.

import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

'''Creation of Firefox Webdriver '''
# driver = webdriver.Chrome()
driver = webdriver.Firefox()
driver.get("https://www.lambdatest.com/")

time.sleep(5)

print("Before refresh")

ActionChains(driver) \
    .key_down(Keys.CONTROL) \
    .send_keys(Keys.F5) \
    .key_up(Keys.CONTROL) \
    .perform()

print("After refresh")

sleep(5)
driver.quit()

Selenium Tip #4 – Open A Webpage In A New Tab

execute_script can be used to synchronously execute JavaScript code in current window/frame. Argument (a JavaScript) to open the webpage is passed as the argument to execute_script

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep

driver = webdriver.Firefox()
driver.get("http://www.google.com/")

driver.implicitly_wait(10)

#open tab
driver.execute_script("window.open('https://www.lambdatest.com', 'new tab')")

sleep(5)
driver.quit()

Selenium Tip #5 – Saving Partial Screenshot Of A Web page

There are cases where you might need to take a partial screenshot of a webpage as your perform test automation with Selenium. In such cases, you can make use of the Pillow module. You need to first install the Pillow/PIL module using the command

pip install pillow

Screenshot of the entire webpage is taken using the get_screenshot_as_png() API. Once the screenshot is ready, the PIL library is used to open the captured image in memory, after which the image (which contains the entire webpage screenshot) is cropped to get the resultant image.

from selenium import webdriver
''' Install the Pillow module using the command pip install pillow '''
from PIL import Image
from io import BytesIO

driver = webdriver.Firefox()
driver.get('http://google.com/')

# Use the Inspection tool to find the location of the logo
element = driver.find_element_by_id('hplogo')
image_location = element.location
size = element.size

png = driver.get_screenshot_as_png()

''' Since the webpage screenshot is ready, we can exit the browser.'''
driver.quit()

''' PIL Library is used to open the image in memory '''
crop_image = Image.open(BytesIO(png))

''' Extract the Left, Right, Top, and Bottom co-ordinates ''' 

left = image_location['x']
top = image_location['y']
right = image_location['x'] + size['width']
bottom = image_location['y'] + size['height']

crop_image = crop_image.crop((left, top, right, bottom))
crop_image.save('logo-screenshot.png')

Selenium Tip #6 – Execute JavaScript Code

execute_script is used to execute JavaScript code as you perform test automation with Selenium WebDriver. The syntax is driver.execute_script(“javascript code here”).

As shown in the example below, a on_click action of Register is performed [Class name is home-cta].

from selenium import webdriver
from time import sleep

driver = webdriver.Firefox()
driver.get("https://www.lambdatest.com")

driver.execute_script("document.getElementsByClassName('home-cta')[0].click()")

sleep(10)

driver.close()

Selenium Tip #7 – Extracting Results Of JavaScript Code

After invoking the JavaScript code for automation testing with Selenium, you need to extract the results of these JavaScript codes. You can make use of the return keyword in order to get the result of a JavaScript code as shown in the extended example where we explained JavaScript.

from selenium import webdriver
from time import sleep

driver = webdriver.Firefox()
driver.get("https://www.lambdatest.com")

driver.execute_script("document.getElementsByClassName('home-cta')[0].click()")
    
result = driver.execute_script("return 0")
print(result)

sleep(10)

driver.close()

Selenium Tip #8 – Handling Multiple Browser Types For Automated Cross Browser Testing

There are multiple scenarios that you might need to test your code against different browsers e.g. Firefox, Chrome, Internet Explorer. The practice of testing a website across different browsers is termed as automated browser testing. To perform automated browser testing with Selenium automation testing, you should incorporate selective handling of those browsers in your unittest code or pytest code. A code snippet (which makes use of pytest) to handle multiple browsers is shown below:

# Import the 'modules' that are required for execution

import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from time import sleep

#Fixture for Firefox
@pytest.fixture(params=["chrome", "firefox"],scope="class")
def driver_init(request):
    if request.param == "chrome":
        # Perform necessary actions here
    if request.param == "firefox":
    # Perform necessary actions here
    yield
    web_driver.close()
    ...........
    ...........

AUTOMATED CROSS BROWSER TESTING

SELENIUM GRID 2000+ Browsers

FREE SIGNUP

Selenium Tip #9 – Locating Elements On A Web Page Using CSS Locators

As you perform test automation with Selenium, locating web elements on a page comes as a foundation to your automation scripts. In case you want to perform conditional execution based on the presence of a particular kind of web element like Tag, Class, ID, etc. you can make use of find_elements_*** API. Some of them are mentioned below

  • find_elements_by_class_name – Find elements by Class Name
  • find_elements – Find elements by strategy and locator
  • find_element_by_link_text – Find element by link text
  • find_element_by_partial_link_text – Find element by partial match of link text

Shown below is the usage of find_element_by_partial_link_text & find_elements_by_class_name where the elements are searched on https://www.lambdatest.com/ which is the URL under test.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Firefox()
driver.get("https://www.lambdatest.com")

try:
    element = driver.find_element_by_partial_link_text("START TESTING")
    print("Partial text Element found")
    element = driver.find_elements_by_class_name('home-btn-2')
    print("Button Element found")
except NoSuchElementException:
    print("No element found")
    
sleep(10)
driver.close()

Check Our Blog Series For A Detailed Read About Various CSS Locators Used For Test Automation With Selenium.

Selenium Tip #10 – HTML Source Of WebElement

innerHTML property can be used to capture the source code of a WebPage. innerHTML is also used to examine any changes in the page since the page was first loaded by the web browser. You can write the entire source code in a .html file for future reference.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from time import sleep
import io

driver = webdriver.Firefox()
driver.get("https://www.lambdatest.com")

elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("innerHTML")

filename = open('lambdatest_page_source.html', 'w')
filename.write(source_code)
filename.close()
    
sleep(10)

driver.close()

Selenium Tip #11 – Perform Mouse Over Actions

There would be scenarios where you might need to perform a click on an item which is a part of the menu or an item which is a part of a multi-level menu. First we locate the Menu item and then perform a click operation on the intended menu item.

In the example below, the URL under test is https://www.lambdatest.com/. The intent is to navigate to the Automation Tab on the home page. The first task is to locate the Menu which matches the ID bs-example-navbar-collapse-1. By using the Inspect Tool, we get the correct element-id, details is as shown in the snapshot

We move to the Menu using the move_to_element operation which is a part of the action_chains module. Next task is to locate the Menu item which contains the text ‘Automation’ for which we make use of find_element_by_xpath(“//a[contains(text(),’Automation’)]”) after which Click operation is performed.

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
    
driver = webdriver.Firefox()
driver.get("https://www.lambdatest.com")

action = ActionChains(driver);

# Head on the top-level menu on Lambdatest website
parent_level_menu = driver.find_element_by_id("bs-example-navbar-collapse-1")
action.move_to_element(parent_level_menu).perform()

# Perform a click operation on the Menu item which contains text Automation
child_level_menu = driver.find_element_by_xpath("//a[contains(text(),'Automation')]")
child_level_menu.click();

sleep(10)

driver.close()

Selenium Tip #12 – Closing Tabs Without Closing The Browser

One of the most basic yet mandatory tips for any test automation Selenium script is to realize how to close tabs without closing the entire browser. driver.close() closes the focused tab and driver.quit() will close all the tabs (of the browser) along with quitting of the driver. In case you need to keep the browser window open (and quitting all other tabs), you can make use of switch_to.window method which has the input parameter as window handle-id.

Note – There are other methods to approach this problem. window.open method can be used with appropriate options (i.e. opening new window, opening new tab, etc.). Sending the right key combinations using send_keys can be used, but the behavior has dependency on version of geckodriver (for Firefox), version of chromedriver, etc. Hence, send_keys approach is not preferable since the output can vary based on WebDriver versions.

In the below example, we open one new window which contains the test URL and close other windows. We only make use of window_handles to achieve the requirement.

from selenium import webdriver
import time
 
driver = webdriver.Firefox()
driver.get('https://www.google.com')
# Open a new window
driver.execute_script("window.open('');")
time.sleep(5)
# Switch to the new window since the focus would still be on the old window
driver.switch_to.window(driver.window_handles[1])
driver.get("https://lambdatest.com")
time.sleep(5)
# close the active tab
driver.close()
time.sleep(5)
# Switch back to the first tab
driver.switch_to.window(driver.window_handles[0])
driver.get("https://www.yahoo.com")
time.sleep(5)
# Close the only tab, will also close the browser.
#driver.close()

Selenium Tip #13 – Handling Drop-Down Menu In A Page

There is a requirement where you have to select a particular option from a drop-down menu present in a web-page. There are a number of ways in which you can select the desired option from the drop-down menu.

  • select_by_index(desired_index_value)
  • select_by_visible_text(“text_to_be_selected_from_drop_down_menu”)
  • select_by_value(value)

We will use http://demos.dojotoolkit.org/dijit/tests/test_Menu.html for Selenium automation testing on this requirement. Before we select the required element from the drop-down menu, it is important to get the ID of the element under test. We use find_element_by_xpath method to locate the element and once we have located the element (using the ID), we select the value from the drop-down menu.

In the example below, we have shown the different methods through which you can select an element from the menu (@aria-label=’select’)

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from time import sleep
from selenium.common.exceptions import NoSuchElementException
from pip._vendor.distlib import resources

driver = webdriver.Firefox()
driver.get("http://demos.dojotoolkit.org/dijit/tests/test_Menu.html")

''' Let the page load completely '''
sleep(5)

try:
    ''' You can derive these details by using Web Inspector '''
    select_element = Select(driver.find_element_by_xpath("//select[@aria-label='select']"))
    # Option 1 - Selecting the drop-down item by using the text
    select_element.select_by_visible_text("bleed through")
    sleep(5)
    # Option 2 - Selecting the drop-down item by using the index value
    select_element.select_by_index(0)
    sleep(5)
    # Option 3 - Selection of desired option using value
    ''' This option would fail since there is no value in the page
     which we are testing right now ''' 
    # select_element.select_by_value('2')
except NoSuchElementException:
    print("Element not found")

''' Addition of delay so that we can have a look at the output '''
sleep(5)

''' Release the resources '''
driver.quit()

Selenium Tip #14 – Handling Operations With Check Boxes

Check boxes are common elements in web pages which are used in scenarios where you have to select only one option from a number of options. Like drop-down menu handling, we locate the required checkbox using find_element_by_xpath method and once we find the checkbox, a click operation is performed.

We will use http://demos.dojotoolkit.org/dijit/tests/form/test_CheckBox.html for Selenium automation testing and the requirement is to ‘check’ the checkbox which has the value cb7: normal checkbox. The matching is done using driver.find_elements_by_xpath(“//*[contains(text(), ‘text to be searched’)]”).

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from time import sleep
from selenium.common.exceptions import NoSuchElementException
from pip._vendor.distlib import resources

driver = webdriver.Firefox()
driver.get("http://demos.dojotoolkit.org/dijit/tests/form/test_CheckBox.html")

''' Let the page load completely '''
sleep(20)

try:
    ''' You can derive these details by using Web Inspector '''
    driver.find_element_by_xpath("//*[contains(text(), 'cb7: normal checkbox')]").click()
except NoSuchElementException:
    print("Element not found")

''' Addition of delay so that we can have a look at the output '''
sleep(5)

''' Release the resources '''
driver.quit()

Selenium Tip #15 – Selecting Element via CSS Selector

There is a provision to locate elements on a webpage using the CSS locator as..

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

JavaScript is without a doubt one of the most in-demand programming languages in 2019. It has been the pinnacle of modern web development from decades. Worldwide adoption of JavaScript has also led to the introduction of many frameworks to help ease the life of a developer. Many JavaScript flavors also came into the picture but went without receiving enough attention from the web developers or testers community, even if that flavor is introduced by industry giants. One such example would be Facebook’s Reasonml: a JavaScript flavor 52% of developers don’t know about. Facebook came with Reasonml in 2017 and even after being around for a couple of years, more than half of the web community was unaware of its existence. So we know that with a plethora of JavaScript frameworks, choosing the right one for you could be a challenging task.

It is why we have come up with an infographic which highlights key statistics from the StateofJS survey of 2018, & SimilarTech, to help you realize the top JavaScript frameworks for 2019.

If you are curious for a detailed comparison between these frameworks then refer to our blog post on “Top 11 JavaScript Frameworks For 2019”.

Share this Image On Your Site

Please include attribution to www.lambdatest.com with this graphic.

<a href='https://www.lambdatest.com/blog/infographic-top-javascript-frameworks-for-2019/'>
  <img src='https://www.lambdatest.com/blog/wp-content/uploads/2019/06/Infographic-Design-2.jpg' alt='Top JavaScript Frameworks To Look Out For In 2019' 540px  />
</a>

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

The obsolete conventional methods of software developments were not taking over the escalated market trends, and those methods lacked solutions for the increased demand of quick software release that introduced the “Continuous Integration (CI) and Continuous Delivery (CD)”. Along with CI/CD, you need to have that kind of technical capability where developers adapt to the shortened delivery cycles and automation processes. Keeping up with the acceleration of change in the testing world, you need to deepen, broaden, and make a strong network with other QA professionals also. Easier said than done, I know! I have often observed the struggle involved in implementing a CI/CD pipeline release cycles, improper resource management, unrealistic ETAs, hesitation involved in task management from a QA manager point of view. Which is why, I intend to talk about the rise of CI/CD pipeline, common challenges, and actionable insights every QA should follow, to cruise swiftly & safely through every release using a CI/CD pipeline.

Why CI/CD Pipeline Became An Obvious Choice To A Majority Of Organizations?

Sooner or later, by now, testers went on shifting towards Continuous Delivery in projects and organizations. The teams opted for the CI/CD pipeline to take advantage of the perceived benefits of a quick release build, that was at the push of a button. Businesses need faster feedback, consequently vastly improved time to market. This led to an increase in worldwide adoption of CI/CD pipeline. In personal experience, CI/CD pipeline left an impact on how I used to approach my testing as it helped my team to accelerate the go-to-market launch.

My developer friends had little hunger for testing approaches, especially the lengthy testing phases that were never found to keep up with the pace of delivery. Continuous Delivery becomes right up to developers’ alley when they get rapid feedback on their code. The moment they check in, they get the signal if they mistakenly introduced some kind of issues within the build pipeline comprising different layers of testing. Without even test automation, you have a tendency to know the feedback from live users – a direct connection from your customer base. Developers never cripple with fast feedback and hence enhance the production. Build pipeline reduces the waiting time expected for integration and release testing. That means that everything happens at one go: write code – test locally – review – merge – integration – and into the tester hands. One of the key parts is test automation where a company can focus on continuous integration and continuous delivery of the software. A single click can land the executable to an environment, that is local, test or production. Best practices in CI/CD pipeline can deliver the product in high quality.

Selenium Grid Of 2000+ Browsers

Integrations With CI CD

FREE SIGNUP

Importance of CI/CD pipeline became evident with time demanding for agile, kanban and other latest SDLC approaches. But how do we as a professional QA should go about managing ourselves in a CI/CD pipeline. Let’s find out.

Rational Steps Every QA Should Note For A Successful CI/CD Pipeline

In the CI/CD pipeline, a technical part could be a trap for the testers. Basically, their duty entails more than that: all the attention to the requirement, practices, products, and processes. Should you start working in a Continuous Delivery environment – Contemplate x 10 times! Think about:

  • Whether the team is heading in the right direction?
  • If all the business requirements have transformed into executable specifications?
  • As a QA tester in what way you are going to contribute in terms of scenarios, acceptance criteria, and examples.
  • Do you think already floating processes have room for improvement? Are you able to detect the waste and remove that waste finally?
  • Your experience about non-functional testing, performance, accessibility, and security etc.
  • Cross browser testing to ensure your changes looking good to the audience who is viewing your web-application from different browsers, browser versions, devices, and operating systems.
  • Calculating your ROI on test automation with Selenium for automated cross browser testing.
  • The difference between cross browser testing & responsive testing. Both the testing practices are often misinterpreted as one & the same. However, they are not!
  • Version Control, being a cornerstone of CI/CD pipeline enable developers to collaborate on a shared codebase. Version control is an absolute must and a great companion of CD. You have the undo functionality in version control system means rollbacks to the previous release. In addition, configuration, databases, scripts, documentation can be tracked throughout history.
  • Data and configuration required across all the staging environments. Keep in mind, the 13 reasons why the staging environment is failing for your organization.
  • Creating automated stable tests across the entire application with test frameworks and automated tools
  • A deep insight: no code or feature remain untested that can further decrease in speed consequently; holding back your team to release the software at times.
  • A good tracking mechanism to maintain the effectiveness of the regression test suite clearly outline a process and ensuring only useful tests are added to the test suite, having a consolidated view of all the quality activities as you keep regression defects in check.
  • Automatic code commits, test suites, and test environment produces immediate feedback, and when you turn to CI/CD pipeline, it automatically resolves issues like version control, or when coders would write unit tests which are often found tough to turn into a workflow. Upholding the desired level is the key point of Quality assurance. QA means the inclusion of growing ideas and long-term maintenance and three important points that can be brought to the surface are: Testing, Delivery, and Optimization.
  • How other QA member would write test packages to run them automatically during every successive build? Maintaining them within a CI system makes the test suites more organized and easily accessible.
  • You need a Continuous Integration Server to monitor the main repository where you will be running the automated tests for newly submitted commits.
  • Specific roles of developers who would deal with merging the changes as often as possible.
  • Development lifecycle starts with checklists or playbooks comprising the tasks that happen to be performed manually. Later on, those tasks could move to automation with scripts and tools. With that, you ensure tasks are repeatable as a team member can run the script if the checklist needs to be run again. Moreover, you run playbook scripts consistently between environments, you increase the reliability like a script for deploying code mirror the production environment.

QA doesn’t limit itself within the fundamental aspects of the why & how to create a front-end website testing plan, in fact, it adds value to the organization. As much as you tend to optimize QA, the greater the chances of a faster product cycle increases. And with fast feedback loops, you can outpace the result.

Thorough testing plays an important and crucial role in the success of a software product. Always think twice, thrice about the test cases to automate, and to get the most out of it, start as early as possible. Starting out from day one gradually build your automated suite that can detect bugs at a much cheaper price rather that you find the same issues in later stages of your cycle. Squeezing test in at the end is a lot more problem so keep on figuring out the following:

  • How frequently you are going to repeat the scenario?
  • The length of the process.
  • Enlist all the recurring test cases that gets executed for multiple builds.
  • Check the people and resources dependencies involved and any shortfall or delay that might cause due to them.
  • If you are skipping the automation at any place, ensure it will not turn out to be an error-prone process.
Most Common Challenges For Every CI/CD Pipeline
  • Developers devote 20-40% of dedicated time to debugging. That means, spending an increasing percentage on debugging software rather than building new features results in reverse outcome, and thus loss of productivity, uncontrolled spending, and employee churn.
  • Even the most thorough testing, staging, and QA process could allow slipping errors through the cracks, so always be ready to face unexpected, or disruption, and breaking the code often in CI/CD pipeline.
  • Engineering teams face the challenges even after the code is deployed as the cycle becomes more uncontrolled when you don’t add automation to your monitoring process. Outdated production monitoring practices often stall a CI/CD process, and an informed production error handling strategy should come in place to mitigate the associated risks.
  • Error-prone tasks, addressed at a time could prevent enough loss of energy like a painful chore might consume more than 20 minutes and multiply by 5 times for a week, would compound to a 100 painful minutes. So for a healthy dose, address the chore and optimize at the initial stage and thus preventing a painful time altogether. On this front, do the hardest part first that will further analyze and identify weaknesses in the organizational process. The procrastinated task is an indicator to an area of improvement so a team should pursue or keep them at the forefront to resolve it at the earliest.
  • Website business has nothing to do if an app is working solely on a developer’s machine. Overall business goal and empathy should be the key responsibility of each team member. CI/CD pipeline is entirely meant to ship code changes to the website for an end user’s convenience. So when you “done”, ensure the entirety of the team’s responsibility and contribution is complete.
Actionable Insights For Every QA To Implement A Robust CI/CD Pipeline

Other than the rational thought process, as a professional QA, you are responsible for every minute change that takes place in the production environment. Slacking off on any release cycle could lead to a flood of outages. Which is why it becomes imperative to keep a checklist on all the actionable insights one needs to take care of for ensuring a successful CI/CD pipeline.

Test Automation With Selenium For Automated Cross Browser Testing

Your website is the identity of your business on the internet, and it would be terrible if it starts looking weird on some browsers and devices after your recent code changes in production through CI/CD pipeline. Cross browser testing is a process to measure how well a website would fare against different rendering engines of different browsers and browser versions.
Test automation with Selenium can help pace your things up a lot faster, resulting in the faster go-to-market launch with the help of parallel testing in Selenium.

LambdaTest provides you with a cloud-based cross browser testing tool which offers a Selenium Grid of more than 2000 real browsers along with integration to numerous CI/CD tools such as Jenkins, Travis CI, CircleCI, and more.

Exploratory & Automation Testing

Our regular readers would know our main emphasis lies in the ability to test at the speed. Maintaining the quality and what value a QA holds for every CI/CD pipeline, I am going to share with you the experience of how we focussed on the testing programs to adjust with CI and agile approaches to development. Exploratory testing is pivotal for a successful CI/CD pipeline, and you can blend it with automation so as to make a growth in testing and business as well. Learn more from Exploratory Testing: It is all about discovery!

All facets of the company in QA needs to be determined when you start integrating QA in the process. Once you have known what needs to be automated, go for it & automate. Functional testing can’t sit in automated testing place because you don’t know what you could program next. In that type of scenario, we blended it with automated test creation depending on the exploratory bugs. Now, the build is filtered after the functional exploratory testing for automating the testing of remaining bugs. Your cognitive skills in functional exploratory testing bring you to a point when you start assembling all the features to test and turn the QA into a gatekeeper for release. Developers start releasing the build to CI/CD servers for the QA department who conducts the test before release using a sturdy CI/CD pipeline.

Functional and UI testing

Functional and UI testing both are repeated at least once per day, and require 2 – 3 hours for a medium-sized application. In the case of test automation with Selenium, there is no need to update the automation script frequently, but UI often gets modified, thus require frequent script changes. Both depend on multiple dependencies and both are error-prone and when we have to decide which one to prioritize, I would say bring functional testing before UI testing that makes the best use of resources.

Automated Regression Testing

Regression Testing is used when a developer makes changes to functionality or repairs a bug. The CI system serves as a QA tool for automated regression testing suites for long-standing products, working well for Agile development where teams are supposed to deploy a product at least weekly and have shorter deadlines to accommodate manual regression testing. Another advantage is you can use the infrastructure for your future products and hence accelerating test automation. CI automatically adds new test cases when a new defect is found. The CI builds upon itself a substantial regression test suite running automatically against the new code.

With LambdaTest, you can perform test automation with Selenium in parallel for executing your automated regression test suites over different browsers, browser versions, simultaneously.

Aligning the Agile Testers & Developers

I believe it will always be unfortunate if the quality is portrayed as an after-the-fact, meaning you first underline the requirements and then design, coding, and finally shifting the gears towards quality and say: “let us bring some testers”. Testing or the whole quality is absolutely is an important aspect when you have to ship your products as early as in a week or month. Agile methodologies break down the software development into user stories (smaller tasks). This results in faster feedback, and go-to-market launch. Helping you develop better web-apps, faster. With CI/CD pipeline you can validate your web-application on a more frequent basis. However, automating all facets of building, integrating, testing, and deploying software mitigate risks. And if you see it in the context of Agile vs Waterfall methodology, Agile rapidly leaves behind waterfall methodology by supporting a process in which requirements are expected to change and evolve frequently. While developing websites with frequent overhauls, keeping pace with technology landscape, customer requirements, agile addresses the needs of developers with the selection of effective automation processes. Check out our read on “What I Learned While Moving From Waterfall To Agile Testing?

Don’t Start Test Automation With Selenium If You Are Clueless!

Sure, there are benefits to test automation with Selenium. However, without a strategy, you could end up using a complex code for a simple code testing. It is important to analyze how different parts can be automated. Undertaking an automation initiative shall not be overlooked but the strategy shall help us meet our goals. I always recommended isolated unit tests which are supported by every language. Fast running unit tests boost the confidence level and ensure the correctness of code in mere seconds. If unit tests fail, no need to move further. Pass unit test implies components are doing well and application is building up all according to the customer expectations. Yes, BDD is the best practices for writing better-automated tests. Here are 8 actionable insights for writing better automation code.

Selecting The Right Automation Testing Tool Based On Your Project Requirements

You can see the widespread market of the automated testing tools, and the important thing is to select the right testing tool that suits your overall requirement: It should support platform and technology like C#, Java, or .Net applications and using which operating systems? Furthermore, take your decision based on whether you need to test web application, or mobile application: Android or iOS or both the operating system. For example, if you wish to perform automated cross browser testing, then Selenium being a reliable open-source comes as the first choice. However, there are still some limitations to it, if you opt for on-premise test automation with Selenium. You are limited to the number of browsers on which you can test in parallel using Selenium Grid. Also, the Selenium Grid to run say 4-8 parallel test sessions would need a very solid hardware requirement. An optimal solution for that would be considered as a cloud-based cross browser compatibility testing tool such as LambdaTest.

LambdaTest offers a Selenium Grid which is compatible with every framework and language that supports Selenium. You get to perform test automation with Selenium on-cloud, at scale. You also get integrations to numerous third-party project-management tool, CI CD tool, along with their Chrome Extension & their WordPress Plugin.

LambdaTest also offers Open Selenium API to help you extract your test details, test reports of your test automation Selenium script execution from LambdaTest platform to your preferred system, without logging into LambdaTest.

Incorporate Continuous Testing In Your CI/CD Pipeline

Continuous testing is a process of evaluating an E2E evaluation of your web-app using a comprehensive range of automated test suites. It ensures quick circulation around feedbacks and upcoming sprints.

CI systems are not restricted to code-level unit tests and can even perform integration testing on interdependent platforms at once. Don’t use integration testing to test business logic, that’s what unit tests are for. CI system run unit tests very fast for every build. Integration testing takes much longer to run whereas unit tests target basic correctness of the code. Units tests should flush out all the bugs of business logic.

Incorporating continuous testing in your CI/CD pipeline, and empower your QA team with faster evaluation using test automation and feedback. Check out our readers to know more about implementing continuous testing in DevOps like a pro.

Introduce Fault Injection Testing For Better Test Coverage Of Your CI/CD Pipeline

As the name suggests, Fault Injection Testing is where you intentionally push faults into your code for enhancing the sturdiness of a web-application, along with the test coverage. Introduce the fault injection testing as a standard part of a review and when your processes and practices get mature, it will ensure the web-application’s resilience. Indeed it is a good practice when you are able to analyze the results of bugs or errors infused in advance before they appear in the production. Though you can conduct the Fault injection tests manually, however, there are tools available for it as well.

Don’t Leave Failing Tests Unattended

A certain level of discipline is necessary for the team that stops to skip any failing test & when you are holding it temporary (i.e. throw SkipException) or using a tool to mute, place the proper comment for the time being and ensure it does not remain unattended or ignored a bit longer in the configuration. A single build does not contain a lot of changes, so reviewing the build time to time can locate the tests. In fact, Reviewing builds with certain changes helps you in identifying any broken test. And the CI/CD pipeline must be stable with a trunk that tells you if a build has failed, either by notification via email or IM. TeamCity provides numerous features and one of them letting you know — who is taking care of failing test.

LambdaTest offers integration with TeamCity to help you fast-track automated cross browser testing on every commit made along with your CI/CD pipeline.

Keep Load Clashes In Mind

CI/CD pipeline incorporates testing to ensure the delivered build is stable and bug-free. While adhering to CI/CD pipeline, reporting of issues is the key factor. A full report furnishes the details on how the tests were run and if anyone failed, the reason behind it. Have you ever tested a web server for performance? Which tool did you use? I would reckon 60% chances are it was JMeter. This tool simulates real-user behaviors and gives sophisticated reports.

The best thing is, Jmeter works with selenium Grid to check the software performance under the multiple and concurrent user traffic. Maven, Jenkins, and Selenium can be used together to create good end-to-end reports, create APPDEX(Application Performance Index), and the documented behavior of the application by hitting browsers concurrently. I have included the performance testing in the talk so that you can mark it since the beginning to avoid unexpected load clashes.

A Meaningful Dashboard

Indeed testing earlier and faster is cumbersome without automation. One of the major challenges for any CI/CD pipeline lies with the collaboration among various teams or departments such as DevOps, QA, Security team, etc. working to bring a common web-application in the market. You would require a place or rather a dashboard that is transparent to all and relays meaningful and organized information. CI/CD tools like Jenkins, Git, and Jira enables teams to coordinate seamlessly and a meaningful dashboard which was customized by assessing what data everyone wants will matter most to your..

  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview