Skip to main content

Write data from Excel file and Capture ScreenShot Using Selenium WebDriver



File Read and Write is a basic piece of any product or software process. We as often as possible make a document, open it, and update something or erase it in our Computers. The same is the situation with Selenium Automation. We need a procedure to control records with Selenium. 

Java gives us various classes to File Manipulation with Selenium. In this article, we will figure out how might we Read Data on Excel documents with the assistance of the Java and Apache POI library.
Learn Automation testing





Installing JAVA in your System.

TestNG requires Java which means you should download and install Java on your system. In my previous blog, I have shown how to install JAVA on your computer in detail. Here is the link  https://modtechstuff.blogspot.com/2020/05/how-to-start-automation-using-selenium.html

Eclipse Installation

Eclipse IDE is one of most liked Java development, though it’s hard to deny it has been losing ground to IntelliJ recently, Eclipse composed for the most part in Java and its essential use is for creating Java applications, yet it might likewise be utilized to create applications in another programming language including C, C++, C#, COBOL, D, Erlang, Fortran, Groovy, Haskell, JavaScript, Julia, Perl, PHP, Prolog, Python, R, Ruby, Scala, and Scheme. It can likewise be utilized to create archives with LaTeX (by means of a TeXlipse module) 
In my previous blog, I have shown how to install ECLIPSE on your computer in detail. Here is the link  https://modtechstuff.blogspot.com/2020/05/how-to-start-automation-using-selenium.html

TestNG Plugin Installation.

After Succesful installation of Eclipse IDE, we have to install a TestNG plugin
When you Launch Eclipse IDE for the first time, you will see a welcome screen like shown below
                   Eclipse IDE


The next step is to click on ‘Help’ and go to Eclipse Market Place and in search text box write TestNG and Press GO Button.


Eclipse IDE


You will see TestNG for Eclipse, click on the install button, in my case, I  have already installed TestNG plugin on my machine


Eclipse IDE


After installing the TestNG Plugin,  Eclipse is restarted, click on File-> New-> Java Project.

                                         Eclipse Project


The next screen will display Java Settings. Go to Libraries and click on Add Library.

Eclipse Ide


Select TestNG and click next. TestNG is now ready for use.

Eclipse Ide


Eclipse Ide


The next step is to create a TestNG File by Opening Eclipse and go to Package Explorer view. Select the test project you named earlier.
 Right-click on src and choose new 
->other

TestNG


Now click on TestNG and it will display TestNG Class.
TestNG Class

On the next screen, it will ask you to enter new TestNG class details.
TestNg class

After clicking on the finish button, you will see a screen like shown below
Eclipse IDE


Congratulations Eclipse will now create your TestNG template automatically and You can start writing your code!

What is Selenium?


Selenium is an open-source automated testing tool used to automate web applications.  You can utilize various programming languages like Ruby, Java, NodeJS, PHP, Perl, C#, Python, and so on to make Selenium Test Scripts. Testing done utilizing the Selenium tool is generally term as Selenium Testing. 

Selenium Software isn't only a single tool however a set-up of different software, each piece taking into account distinctive testing needs of an association. To begin with Selenium's most recent adaptation (WebDriver-based usage), you'll just need a single selenium JAR file (selenium-independent server-'{'version'}'.jar) to run tests both locally and on remote systems.


Brief History of Selenium:

Selenium was developed by Jason Huggins in 2004. An architect at ThoughtWorks, he was taking a shot at a web application that necessary successive testing. Having understood that the tedious Manual Testing of their application was turning out to be increasingly wasteful, he made a JavaScript program that would consequently control the program's activities. He named this program JavaScriptTestRunner.

The Selenium name originated from a simple joke in which Jason broke one an opportunity to his group. Another automated testing structure was mainstream during Selenium's turn of events, and it was by the organization called Mercury Interactive (indeed, the organization that initially made QTP before it was procured by HP). 

Components of Selenium Suite:

  • Selenium (IDE)
  • Selenium Remote Control (RC)
  • Selenium WebDriver
  • Selenium Grid

Selenium IDE:

Selenium Integrated Development Environment (IDE) is the most simple system in the Selenium suite and is the least demanding one to learn in the present scenario. Due to its simplicity, the Selenium IDE should just be utilized for only a prototyping tool. If you further develop advanced test cases, you should employ either Selenium RC or WebDriver. 

Selenium RC:

Selenium RC was the lead testing system of the entire Selenium venture for quite a while. This is the primary automated web testing device that permitted clients to utilize a programming language they like. As of form 2.25.0, you can use Java, Ruby, Python, C#, Pearl in Selenium RC. 

Selenium WebDriver:

The Selenium WebDriver demonstrates itself to be better than both Selenium IDE and Selenium RC in numerous perspectives. It actualizes a progressively current and stable methodology in the automation of the browser activities. WebDriver, not at all like Selenium RC, doesn't depend on JavaScript for Automation. It controls the browser by legitimately communicating with it. Selenium RC is compatible with Java, Ruby, Python, C#, Pearl. 


Selenium Grid:

Selenium Grid is a tool utilized along with Selenium RC to run equal tests across various machines and various browsers simultaneously. Equal execution implies running different tests immediately. 
Allows concurrent running of tests in numerous browsers and environments. 
Save time effectively. Uses the nodes and-hubs approach. The hub works as a  central source of Selenium command to every node associated with it.

Which Selenium YOU need?

1. Selenium IDE:

To find out about approaches on automated testing and Selenium, including: 
Selenese commands, for example, type, open, clickAndWait, attest, confirm, and much more. Locators, for example, id, name, xpath, css selector. Executing customized JavaScript code utilizing runScript To develop tests with no earlier practical knowledge in programming. To make simple test cases and test suites that you can send out later to RC or WebDriver.

2. Selenium RC:

To structure a test utilizing a more expressive language than Selenese 
To run your test against various programs (with the exception of HtmlUnit) on various working frameworks. 
To send your tests over numerous situations utilizing Selenium Grid, the application against another program that underpins JavaScript and web applications with complex AJAX-based situations. 

3. Selenium WebDriver:

To utilize a specific programming language in structuring your test cases. To test applications that are using more AJAX-based functionalities.
To execute tests on the HtmlUnit program. 

4.Selenium Grid:

To run your Selenium RC contents in numerous test cases and working frameworks in parallel. To run a large number of the test suite, that can be finished as soon as possible.


Why do I need Selenium Automation Testing?

Let us suppose you are a  manual tester who has this situation: Checking whether the Facebook sign up page approves input strings and registers a customer effectively in most recent versions of Chrome and Safari. 
Accept that the sign-up page has these info fields—username, email address, and password. The tester will get a Windows 10 And Mac OS and follow these means, successively, on most recent variants of Chrome and Safar. 

Enter the URL in the location bar (www.facebook.com/signup) 
Enter an invalid string in each info field (email, username, and  password) 
Check whether the information was approved against comparing regexes and  data in the database 
Enter 'valid' strings in each information field; click Sign Up 
Check whether "Welcome to Facebook, '{'username'}'" page appeared 
Check whether the framework database made another userID for '{'username'}' 
Depending upon the number of manual testers it might take a few hours to weeks to be certain that the web application is completely Tested. 

Present-day engineers don't have that sort of time to allow for testing, however, they can't put aside comprehensive testing in a rush to discharge either. This is the reason Selenium comes under the picture.
With the help of Selenium Automation Testing, we can reduce labour time and get more accurate results in no time.

How to Install Selenium:

We can install Selenium in just three steps. The first step is installing JAVA SDK, the second step is installing the Eclipse IDE and finally some Selenium Driver Files.


Step.1 Installing JAVA on your System:

You can download and install JAVA Software Development Kit(SDK)  JDK here

JAVA  JDK


 After clicking on JDK download, you have to choose Your Operating System 
as shown below


JAVA SE

This JDK version comes with an inbuilt Java Runtime Environment (JRE), so the advantage of JDK you do not need to download and install the JRE additionally.


Next step is 

    • Go to Start and search for ‘System’
    • Click on ‘System’
    • Click on ‘Advanced system settings’
    • Click on ‘Environment Variables’ under the ‘Advanced’ tab  as shown below:
    • Under ‘Variable value’, at the end of the line, enter the following path –  %JAVA_HOME%bin; 
    • Now, you can click ‘OK’ and you are done.

Java Path

Once the installation is finished, open command prompt and type " java-version". If you see the following screen, then Congratulations you successfully installed JAVA on your System.

                             Command Prompt



Step.2 Installing Eclipse IDE

Download the latest version of Eclipse IDE  here

Eclipse IDE



After downloading you will get a zip file, unzip it and install. Launch the  Eclipse after a successful installation. When you launch eclipse IDE a popup window will open and asked to select for a workspace, just accept the default location.

Eclipse IDE



The next step is to create a new project through the File > New > Java Project. Name the project as a "new project".

A new pop-up window will open enter details 

Eclipse Project


  1. Project Name
  2. Location to save the project
  3. Select an execution JRE
  4. Select layout project option
  5. Click on Finish button

Step.3 Download Selenium jar File:


Extract the zip file and save it in your selenium folder. Next, you have to download Chrome Driver for Google Chrome and Gecko Driver if you are using Mozilla Firefox. In the same downloads page, scroll further down and you will find third-party drivers section. 
To download driver click here
Selenium Jar File


now next steps are
  1. Right-click on "new project" and select Properties.
  2. On the Properties dialog, click on "Java Build Path".
  3. Click on the Libraries tab, and then
  4. Click on "Add External JARs.."

Eclipse Path Build



selenium\

How to manage excel file using Apache POI library.

To read an Excel file, Apache gives a well-known library known as POI. This library is sufficiently competent to peruse and compose the two XLS and XLSX document configuration of Excel. 
To read XLS records, an HSSF usage is given by the POI library. 
To peruse XLSX, XSSF usage of the POI library will be the decision. How about we study these executions in detail. 

In the event that you are utilizing Maven in your undertaking, the Maven dependence will be required,

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>


You can basically download the most recent form of POI containers from http://poi.apache.org/download.html and download the most recent compress record.



How to Write in excel file

Create a sheet in the workbook and create a row and cells in a sheet. Repeat these steps to write more data.

Here is the complete code to write data in Excel file


package ExcelClasses;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class XLWriteDataInExcel {
private static final String[] ArrColumnName = {"ModuleName", "SubModuleName","TestCaseID",
        "FieldName","Actualresult","ExpectedResult",
        "Status", "Snapshot"};
private static String extn = "xls";

public static void main(String[] args) throws IOException {

Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("TestReport");

CellStyle styleobj = workbook.createCellStyle();

Font fontObj = workbook.createFont();
fontObj.setFontName("Verdana");
fontObj.setColor(IndexedColors.BLACK.getIndex());
fontObj.setFontHeightInPoints((short) 8);
fontObj.setBold(true);
styleobj.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
styleobj.setFillPattern(FillPatternType.SOLID_FOREGROUND);
styleobj.setFont(fontObj);

Row row = sheet.createRow(0);
for(int i=0;i<ArrColumnName.length;i++) {
Cell cell = row.createCell(i);
cell.setCellValue(ArrColumnName[i]);
cell.setCellStyle(styleobj);
}

String FolderName ="Results" ;
String FileName = "Result";
String TimeStamp =  fn_GetTimeStamp();
//String FilePath = FolderName+"/"+FileName+TimeStamp+"."+extn;

String FilePath = "Results/Report"+TimeStamp+".xls";

FileOutputStream fos = new FileOutputStream(FilePath);
workbook.write(fos);
}
private static CellStyle fn_CreateCellStyle(Workbook wBookObj, short ColorNo){
CellStyle styleObj = wBookObj.createCellStyle();
//Short ColorNo = IndexedColors.YELLOW.getIndex();
styleObj.setFillForegroundColor(ColorNo);
styleObj.setFillPattern(FillPatternType.SOLID_FOREGROUND);
return styleObj;
}


private static CellStyle fn_CreateFontStyle(Workbook wBookObj, CellStyle styleObj,int height){
Font fontObj = wBookObj.createFont();
fontObj.setFontName("Verdana");
fontObj.setColor(IndexedColors.BLACK.getIndex());
fontObj.setFontHeightInPoints((short) height);
fontObj.setBold(true);
styleObj.setFont(fontObj);
return styleObj;
}



public static String fn_GetTimeStamp(){
Date dte = new Date();
DateFormat DF=DateFormat.getDateTimeInstance();
String DateValue=DF.format(dte);
DateValue=DateValue.replaceAll(":", "");
DateValue=DateValue.replaceAll(",", "");
DateValue=DateValue.replaceAll(" ", "");
return DateValue;
}

public static void writexldata() throws IOException{
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("TestReport");
Row row = sheet.createRow(1);
Cell cell = row.createCell(1);
cell.setCellValue("Testing");
FileOutputStream fos = new FileOutputStream("Results/Report.xls");
workbook.write(fos);
}

}
How to Take Screenshot in Selenium WebDriver


Screenshots are beneficial for the bug reports. Selenium WebDriver can automatically capture screenshots while execution. You require to typecast WebDriver instance to TakesScreenshot.
Here is the code for Screenshot

package WebdriverBasicConcepts;
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.io.FileHandler;
public class CaptureSnashot {
public static void main(String[] args) throws IOException {

System.setProperty("webdriver.gecko.driver", "Drivers/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
captureSnapshotTest(driver);

}

public static void captureSnapshotTest(WebDriver driver) throws IOException{
TakesScreenshot tss = (TakesScreenshot)driver;
File srcfileobj = tss.getScreenshotAs(OutputType.FILE);
String FilePath = "Snapshot/TestImageNOV.png";
File destfileobj = new File(FilePath);
FileHandler.copy(srcfileobj, destfileobj);
}
}


Wrap-Up

This article discussed how to write data in Excel file Using Selenium WebDriver, please let us know your feedback and also share your experiences and for any query send me a message here. I will ready to help(In FREE).


Author:: HAROON

For more details please visit  MODTECHSTUFF

FOLLOW ME @

      

Comments

  1. Hi there,
    I was really looking for a detailed step by step guide to do this because I was really confused about doing this.
    Thanks a lot, buddy.
    Keep posting good stuff. Cheers.

    ReplyDelete
  2. I like this article.I was searching over search engines and found your blog and its really helps thank you so much

    ReplyDelete
  3. Great Content. It will useful for knowledge seekers. Keep sharing your knowledge through this kind of article.
    Effective Website Design
    Web Design Strategy

    ReplyDelete
  4. Harrah's Hotel & Casino - Mapyro
    Harrah's 경기도 출장샵 Hotel and 청주 출장안마 Casino - Las Vegas. 2 min walk from Harrahs Las 울산광역 출장샵 Vegas Casino and 1.3 mi from Fashion Show Mall. 3 min walk 오산 출장안마 from the Cosmopolitan of 안양 출장샵 Las Vegas

    ReplyDelete

Post a Comment

Donate Us to Keep this site Alive! With PayPal

Popular posts from this blog

How to Automate OTP using Appium and Selenium Framework ?

Hello Everyone! Welcome back to another Fresh article of MODTECHST UFF where you Learn Automation testing. In this article, we will talk about Integrating the OTP SMS reading capability with your Selenium - Appium Framework that will surely help you out. There can be three solutions to this problem. Solution 1: Ask your development team to fix the OTP check process to any static value. Solution 2: Ask your development team to provide you an API in which you can pass some parameter in response he can return you the OTP sent against that number.  Solution 3: Design two Appium scripts one is two handle Websites and one is to handle the Android message box, so after sending OTP from the web execute the second script to read a message from the message box. OTP is a 2-factor authentication mechanism that was build to avoid ROBOT / Automation SO you never find the solution direct solution for that. What is Appium? Appium is an open-source structure that permits you to lead automating testing

How to create my own blog| A complete beginner's guide| Updated(May 2020)

Hello Everyone! Welcome back to MODTECHST UFF.  In this blog, we will talk about How to create your own blog and how to earn from the blog. This guide will provide each and every possible detail about blogging. I realize that beginning a blog can appear to be overpowering and scary. This free guide is tied in with blogging for amateurs and will show you how to be a blogger with simply the most essential PC aptitudes. So whether you're a student or professional, you can make your own blog in just 1 hour!!! I am not afraid to concede that when I was first figuring out how to manufacture a blog I committed a huge amount of errors. You can profit by overtime of my experience so you don't repeat these equivalent mix-ups when you make your own blog. I made this free guide with the goal that anybody can figure out how to blog rapidly and without any problem. What's more, on the off chance that you stall out anytime if you don't mind send me a message and I will give a magnific

Ad

Enter your email address:

Delivered by FeedBurner