How to get the number of count of text boxes present in a page using Selenium WebDriver.

package beginner_level;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class ExtractAllTextBoxes {

public static void main(String[] args) {
System.setProperty(“webdriver.chrome.driver”,”D:\\selenium workspace\\chrome\\new chrome 2\\chromedriver_win32(1)\\chromedriver.exe”);
WebDriver driver = new ChromeDriver();
// Open Google website
driver.get(“https://accounts.google.com/SignUp”);

// In HTML, the  input fields or text boxes are of type- text or password.
java.util.List<WebElement> textfield = driver.findElements(By.xpath(“//input[@type=’text’ or @type=’password’]”));
// Number of text boxes present.
int nsize = textfield.size();
System.out.println(“Number of text boxes are –  ” + nsize);
// Here you can enter the text in the text boxes present in the page and cross check it.
for(int i=0; i< nsize; i++){
textfield.get(i).sendKeys(“Text” + (i+1));
}

}
}

How to set Browser width and height in selenium webdriver.

package beginner_level;

import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SetBrowserWidthHeight {

public static void main(String[] args) {

// Open in chrome browser
System.setProperty(“webdriver.chrome.driver”,”D:\\selenium workspace\\chrome\\new chrome 2\\chromedriver_win32(1)\\chromedriver.exe”);

WebDriver driver = new ChromeDriver();

//Open the railway site – [ http://www.indianrail.gov.in/seat_Avail.html ]

driver.get(“http://www.indianrail.gov.in/seat_Avail.html&#8221;);

// Set the browser width=500 and height = 500
Dimension d = new Dimension(500,500);
driver.manage().window().setSize(d);

}

}

Hope this helps Beginners 🙂

How to run Webdriver in Chrome Browser.

Here I will describe how the application will run in Google Chrome.

1. Go to this link – https://sites.google.com/a/chromium.org/chromedriver/downloads
2. Check your chrome version [ Customize and control Google Chrome → Help → About Google Chrome] and accordingly choose the Chrome Driver.
3. In my system I have chrome 49.0.2623.112 m , so I am opening the Latest Release: ChromeDriver 2.21
Screen shot attached.

1
4. Now according to your OS, download the zip file.
5.My system is windows, so I am downloading – chromedriver_win32.zip .
Screen shot attached.

2

6. Place the downloaded zip file in a folder, extract the zip file and note the path.
7. The exe file will look like the below image –

3

8. Now create a Project in eclipse and a class – “ Chrome_Browser ” and write the below code.

 

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Chrome_Browser {

public static void main(String[] args) {

System.setProperty(“webdriver.chrome.driver”,”D:\\selenium workspace\\chrome\\new chrome 2\\chromedriver_win32(1)\\chromedriver.exe”);

WebDriver driver = new ChromeDriver();
driver.get(“http://www.google.com/&#8221;);
System.out.println(“successful”);

}

}

Hope this helps Beginners 🙂

 

 

BROKEN LINKS AND HTTP ERROR CODES

Broken Links, as the words explain themselves, refer to the links/URL that are unavailable or under construction. There are many reason why the Users get error pages popped up due to these broken links. 404 Error, 500 internal server error, 403 error, unauthorized user error and many more. These are all because of broken links that are framed when error occur when the user wants to be redirected to a page that doesn’t exist. This concept has many names like Link Rot, Link dead, that is in simple language the target of reference does not exist.

This irritates many developers and on the other hand helps them giving the information where and what went wrong. But its developers who can understand but, what about the end users? They should get a valid information regarding what is wrong! For instance, 404 error, what does a user know about this? They should get valid response as page is not available or be navigated to some other default page.

There are many reasons for which a link breaks.

  • The most common reason is that the page is no more available.
  • Some websites also refresh the contents of their respective pages, this might lead to a break if the old contents are searched for.
  • Another reason is that if the targeted page hosted by the server changes, and relates to a new Domain name, then the browser would return a DNS error, or say content unavailable.
  • Dead links or Broken Links occur if the URLs are not organized & proper routing is not done.

To understand the Error, we need to know the Status codes that represent the type of error or success response. They are stated below:-

  • 100-199 : informational status
  • 200-299 : success status
  • 300-399 : redirection status
  • 400-499 : client errors
  • 500-599 : server errors

There are many ways to combat this, but we use XENU.

Xenu is a standalone desktop application for Windows that outputs all your site links, whether they’re valid or invalid links and groups them into a very readable fashion.Xenu’s link Sleuth checks Websites for broken links. Some of its features are:-

  • Can re-check broken links (useful for temporary network errors)
  • Simple, no-frills user-interface

  • Simple report format, can also be e-mailed
  • Executable file smaller than 1MB
  • Supports SSL websites (“https:// “)
  • Partial testing of ftp, gopher and mail URLs
  • Detects and reports redirected URLs
  • Site Map

These broken links need to be avoided as they have many drawbacks that may lead to huge losses to the website also as they would loose many customers.

Now lets discuss briefly about the various HTTP status codes, that is important during the development, so that the error can be notified and easily rectified. For instance, suppose Http status code 404 is returned, that simply means that the page referred by the user doesn’t exist & suppose the Http status code is 500(internal server error) this clearly states that there is problem in the called method or the service, that can be avoided debugging and getting to the root of the error.

HTTP 200 OK:-

The request for the page is processed successfully and the contents are returned or displayed to the user successfully. The users barely see this code as almost everytime a success page with the contents are displayed. Sometimes due to some internal problems the success code 200 is returned in place of the actual contents. This is the reponse from the server to the browser.

HTTP 404 NOT FOUND:-

This error code is self explanatory. As mentioned above , this suggests that the requested page doesnot exist or is unavailable. The server gives nothing in response, but ensures that the connection between client and server was made successfully. Another reason may be with the URL, so the user should be concious during writing the URL.

HTTP 500 INTERNAL ERROR:-

This error suggests that the web server got the request but was unable to process that request, this might be caused due to the problem on the server side and that should be avoided or referred to the server administrator or the developer to rectify the problem.

HTTP 503 SERVICE UNAVAILABLE:-

The reason for this error is almost same as the 500 internal error as the server receives the request from client but is unable to process the request. This might be due to unexpected failure at the web server administrator, increase in the subsequesnt/concurrent request from users.

HTTP 301 PERMANENTLY MOVED:-

The URL specified by the user might be moved to some other locations or have their domain names changed.Using a method HTTP Redirect, the user get redirected to the changed URL and the contents which the user was looking for.

HTTP 400 BAD REQUEST:-

The URL specified by the user must not be present or in developer’s language must not have been implemented, for which the request to the server here returns nothing i.e. Nothing was found as such. Thus, that is mentioned as a bad request, which is coded “404”.

 

Conclusion:-

Thus, here we discussed about the broken links and their causes and how a developer can avoid them from being shown or obstructing the users. This is also very much required for the testers to be aware of about this so that they can test and look for the broken links if any present.Broken Links being irritating for the users should always be avoided to ensure their retention. We also discussed about the different types of Http Error codes that are a part of every website.

Web driver script for Gmail Login Test with valid and invalid test data.

In this article I will be writing script for gmail login using various test Cases.

Test scenario-

CASE – 1 [ Enter Correct user Name and Password ]

  • Check whether Email field exist or not, if exit then write correct email Id
  • Check whether Password field exist or not,if exit then write correct password
  • Check if sign-in button exist or not, if exist then click on sign-in.
  • Check if login was proper or not by comparing the text of Primary tab.
  • Click on the account link containing Sign-Out button and click on Sign-Out button.
  • Check whether Signout was proper or not.

CASE – 2 [ Both Email and Password Fields are blank. ]

  • In the Email field & Password field, don’t  enter any data.
  •  click on sign-in.

CASE – 3 [ Email field is filled and Password field is blank. ]

  • Enter correct Email Id in Email field.
  • In the Password field, don’t  enter any data.
  •  click on sign-in.

CASE – 4 [ Email field is blank and Password field is filled ]

  • Enter correct Password in Password field.
  • In the Email field, don’t  enter any data.
  •  click on sign-in.

CASE – 5 [ Email and Password are entered wrong ]

  • Enter wrong Email Id in Email field.
  • Enter wrong Password in password field.
  •  click on sign-in.

CASE – 6 [ Email is wrong and Password is correct ]

  • Enter Incorrect Email in Email field.
  • Enter correct Password in Password field.
  •  click on sign-in.

CASE – 7 [ Email is correct and Password is wrong ]

  • Enter correct Email Id in Email field.
  • Enter incorrect Password in Password field.
  •  click on sign-in.
  • Close the browser.

Now we will write the code as below.

package package1;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Gmail {
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    // Initialize WebDriver
    WebDriver driver = new FirefoxDriver();

    // Maximize Window
   driver.manage().window().maximize();
  
    // Wait For Page To Load
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

   //Navigate to Google webstites
   driver.get("https://www.gmail.com");

 
/*CASE- 1. Both User name and Password are entered correctly. 
Check whether Email field exists or not */
    try
        {
          WebElement a1 = driver.findElement(By.xpath("//*[@id='Email']"));
          System.out.println("---------Email field exists --------------\n-----------------------");
          a1.sendKeys("ENTER CORRECT MAIL ID");
         }
    catch(Throwable e)
         {
         System.out.println("Email field not found: " + e.getMessage());
         }

    //Check whether Password field exists or not
     try
        {
	 WebElement password = driver.findElement(By.xpath("//*[@id='Passwd']"));
         System.out.println("----------Password field exits ------------\n-----------------------");
         password.sendKeys("ENTER CORRECT PASSWORD");
        }
    catch(Throwable e)
        {
	 System.out.println("Password field not found: " + e.getMessage());
        }

     //Asserting the Sign In button exists or not and clicking it
    try
       {
	WebElement button = driver.findElement(By.id("signIn"));
        System.out.println("-------Sign In button exists----------\n-----------------------");
       //To uncheck the "Check sign in" checkbox
       WebElement check_stay_sign_in = driver.findElement(By.xpath("//*[@id='PersistentCookie']"));
        check_stay_sign_in.click();   
	button.click();
        }
    catch(Throwable e)
        {
	System.out.println("Sign In button not found: "+ e.getMessage());
        }
    //Check if login was proper or not
    try
        {
	WebElement GmailText = driver.findElement(By.xpath("//*[@id=':36']"));
        String text = GmailText.getText();
        if(text.equals("Primary"))
       {
	System.out.println("----------Sucessful Login -------\n-----------------------");
       }else
       {
	System.out.println("----------Login Failure ----------\n-----------------------");
	}
       }
     catch(Throwable e)
        {
	 System.out.println("Inbox link not found: "+e.getMessage());
        }
    //===
    //Asserting and click on the Account link which contain Signout button.
     try
        {
	WebElement person = driver.findElement(By.xpath("//*[@id='gb']/div[1]/div[1]/div[2]/div[5]/div[1]/a/span"));
        System.out.println("--------The Account link containing Signout button exists ---------\n-----------------------");
	person.click();
       }
    catch(Throwable e)
       {
	System.out.println("Link for the drop-down not found: "+e.getMessage());
        }


    //Asserting and clicking on the Signout button.
    try
       {	
	WebElement signout = driver.findElement(By.xpath("//*[@id='gb_71']"));
        System.out.println("--------Sign out button exists  ---------\n-----------------------");
	signout.click();
        }
    catch(Throwable e)
        {
	System.out.println("Sign out button not found: "+e.getMessage());
        }

    //Check whether Signout was proper or not.
    try
       {	
       WebElement GmailText = driver.findElement(By.xpath("//div[@class = 'banner']/h1"));
       String text = GmailText.getText();
       if(text.equals("One account. All of Google."))
       {
       System.out.println("----------Sign out was successful -------");
       }
     else
       {
        System.out.println("----------Sign out wasn't successful ----------");
	}
        }

    catch(Throwable e)
        {
	System.out.println("Sign out link not found: "+e.getMessage());
        }


    // CASE- 2. Both Email and Password Fields are blank.
    try
        {
	WebElement button = driver.findElement(By.id("signIn"));
button.click();			        
WebElement GmailText = driver.findElement(By.xpath("//*[@id=':36']"));
String text = GmailText.getText();
if(text.equals("Primary"))
{
   System.out.println("----------Sucessful Login -------");
}
else
{
	System.out.println("----------Login Failure ----------");
		}
		
}
catch(Throwable e)
{
		System.out.println("Error! Email and Password fields are blank. \n----------------------- ");
System.out.println("Element not found: "+e.getMessage() + "\n-----------------------");
  }


// CASE- 3. Email field is filled and Password field is blank
try
{		
		WebElement email = driver.findElement(By.id("Email"));
email.sendKeys("abcd123@gmail.com");
WebElement button = driver.findElement(By.id("signIn"));
button.click();


WebElement GmailText = driver.findElement(By.xpath("//*[@id=':36']"));
String text = GmailText.getText();
if(text.equals("Primary"))
{
System.out.println("----------Sucessful Login -------\n-----------------------");
}
else
{
System.out.println("----------Login Failure ----------\n-----------------------");
		}
		
 }
catch(Throwable e)
 {
		System.out.println("Error! Password field is blank. \n-----------------------");
System.out.println("Element not found: "+e.getMessage() + "\n-----------------------");
 }	

driver.findElement(By.id("Email")).clear();			// Clearing the Email field


// CASE- 4. Email field is blank and Password field is filled

try
{		
		WebElement password = driver.findElement(By.id("Passwd"));
password.sendKeys("ENTER PASSWORD");
WebElement button = driver.findElement(By.id("signIn"));
button.click();


WebElement GmailText = driver.findElement(By.xpath("//*[@id=':36']"));
String text = GmailText.getText();
if(text.equals("Primary"))
{
System.out.println("----------Sucessful Login -------");
}
else
{
System.out.println("----------Login Failure ----------");
		}
			
}
catch(Throwable e)
{
    	System.out.println("Error! Email field is blank. \n-----------------------");
System.out.println("Element not found: "+e.getMessage() + "\n-----------------------");
 }
  
driver.findElement(By.id("Passwd")).clear();			// Clearing the Password field


//CASE- 5. Email and Password are entered wrong 	

try
{
		 WebElement email = driver.findElement(By.id("Email"));
 email.sendKeys("ENTER INCORRECT MAIL ID");
 WebElement password = driver.findElement(By.id("Passwd"));
 password.sendKeys("ENTER INCORRECT PASSWORD");
 WebElement button = driver.findElement(By.id("signIn"));
 button.click();
 
 WebElement GmailText = driver.findElement(By.xpath("//*[@id=':36']"));
 String text = GmailText.getText();
 if(text.equals("Primary"))
 {
 System.out.println("----------Sucessful Login -------");
 }
 else
 {
 System.out.println("----------Login Failure ----------");
		 }
		 
  }
catch(Throwable e)
{
	
	  System.out.println("Error! Incorrect Email and Password. \n-----------------------");		  
  System.out.println("Element not found: "+e.getMessage() + "\n-----------------------");
}
 
driver.findElement(By.id("Email")).clear();			// Clearing the Email field
driver.findElement(By.id("Passwd")).clear();			// Clearing the Password field
		
	
 // CASE- 6. Email is wrong and Password is correct 	
 try 
 {
	 
		WebElement email = driver.findElement(By.id("Email"));
email.sendKeys("ENTER INCORRECT EMAIL ID");
WebElement password = driver.findElement(By.id("Passwd"));
password.sendKeys("ENTER CORRECT PASSWORD");
WebElement button = driver.findElement(By.id("signIn"));
button.click();
WebElement Inbox = driver.findElement(By.xpath("//*[@id=':53']/div/div[1]/span/a"));
if(Inbox != null) 
{
System.out.println("Sucessful Login \n -----------------");
} 
else 
{
System.out.println("Login Failure");
		}
  } 
 catch(Throwable e) 
 {
	  
	  System.out.println("Error! Incorrect Email. \n-----------------------");
  System.out.println("Element not found: "+e.getMessage() + "\n-----------------------");
  }
 
  driver.findElement(By.id("Email")).clear();			// Clearing the Email field
  driver.findElement(By.id("Passwd")).clear();			// Clearing the Password field
  
  
//CASE- 7. Email is correct and Password is wrong 	
 try
 {
		 WebElement email = driver.findElement(By.id("Email"));
 email.sendKeys("ENTER CORRECT EMAIL ID");
 WebElement password = driver.findElement(By.id("Passwd"));
 password.sendKeys("ENTER INCORRECT PASSWORD");
 WebElement button = driver.findElement(By.id("signIn"));
	 button.click();
	 
 
	 WebElement GmailText = driver.findElement(By.xpath("//*[@id=':36']"));
 String text = GmailText.getText();
 if(text.equals("Primary"))
 {
 System.out.println("----------Sucessful Login -------");
 } 
 else
 {
 System.out.println("----------Login Failure ----------");
			}
  }
 catch(Throwable e)
 {
	   System.out.println("Error! Incorrect Password. \n-----------------------");			  
   System.out.println("Element not found: "+e.getMessage() + "\n-----------------------");
  }

  driver.findElement(By.id("Email")).clear();			// Clearing the Email field
  driver.findElement(By.id("Passwd")).clear();			// Clearing the Password field

//closing current driver window	
		driver.close();
		
	}

}

In the console bar, the output will be seen like this-

2

 

Hope this helps beginners.

Thanks for reading.

Perform right click action using WebDriver

Here is a small tip on how we will perform right click action using WebDriver.

Below is the scenario we will be performing-

    • Open A firefox Browser.
    • Navigate to the URL(http://www.myntra.com).
    • Maximize the window.
    • Now Right click on the Men’s tab present in top navigational bar and click on “Open in a new Tab window”. – For this we will use-
      builder.contextClick(R1).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).perform();
      

sel1

  • For opening the Men tab in a ” New  Window ” , we will use the below code –
    builder.contextClick(hindiLanguage).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).perform();
    

    sel2

Below is the full code-

import java.util.concurrent.TimeUnit;

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

public class Right_click {

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

       // Initialize WebDriver
       WebDriver driver = new FirefoxDriver();
       // Wait For Page To Load
       driver.manage().timeouts().implicitlyWait(120,TimeUnit.SECONDS);
   
       // Go to Myntra Page 
        driver.get("http://www.myntra.com/");
      
       // Maximize Window
       driver.manage().window().maximize();
      
      WebElement R1 = driver.findElement(By.xpath("//a[@href='/shop/men?src=tn&nav_id=5']"));
      
      // Initialize Actions class object
      Actions builder = new Actions(driver);
      
      // Perform Right Click on  MEN and  Open "Men" content in a new tab 
      builder.contextClick(R1).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).perform();
      //ContextClick() is a method to use right click 
    
      /* Perform Right Click on  MEN and  Open "Men" content in a new different Window
      
       builder.contextClick(hindiLanguage).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).perform();
  
      //closing current driver window 
      driver.close();
     */	
		
	}

}



 

So, in this post we discussed how to Perform right click action using WebDriver.

Hope this will help you 🙂

Mouse Hover Action using selenium WebDriver

Mouse events like hovering, clicking on any element of the web page or the main menu and simulating the mouse actions/movements is not that tough in webDriver.  Most of the actions can be performed directly in the webdriver, here I am going to discuss about few of them. We use user interaction API constructor Actions with the moveToElement method to perform the task of monitoring the movements performed by the mouse events.

In mouser action, we use Actions(driver), object.moveToElement(), build(). and perform().

Action class is used to perform keyboard operation and mouse hover operations.

The build() method is used to compile all the listed actions into a single step.

Below is a simple script of  Mouse Hover Action. First of all we will write the scenario of what we will be going to do. Here we will automate the http://www.myntra.com and will perform the mouse hover actions.

    1. Open A firefox Browser.
    2. Navigate to the URL.
    3. Maximize the window.
    4. Now hover on the Men’s tab present in top navigational bar.
    5. Select Bags and Bag-packs from Accessories.
    6. Select the 1st item and add it to the shopping cart.
    7. From shopping cart remove the product which has been added.
    8. Close the browser.
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class mouse_hover { 

    // TODO Auto-generated method stub  
     public static void main(String[] args)throws Exception{
  
     // TODO Auto-generated method stub
     // Initialize WebDriver
     WebDriver driver = new FirefoxDriver();
  
     // Wait For Page To Load
     driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  
     // Go to URL
     driver.get("http://www.myntra.com/");
  
     // Maximize Window
     driver.manage().window().maximize();
  
     // Mouse Over On " Men link " 
     Actions a1 = new Actions(driver);
     a1.moveToElement(driver.findElement(By.xpath("//a[@href='/shop/men?src=tn&nav_id=5']"))).build().perform();
     Thread.sleep(3000L);
  
     // Wait For Page To Load
     driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  
     // Click on " bags & backpacks " link
     driver.findElement(By.xpath("//a[@href='/men-bags-backpacks?src=tn&nav_id=25']")).click();
  
     // click on the categories - Bagpacks
     //  driver.findElement(By.xpath("//*[text()='Categories']//following::li[1]/label']")).click();
     // Hover on the 1st bag 
     Actions a2 = new Actions(driver);
     a2.moveToElement(driver.findElement(By.xpath("//ul[@class='results small']/li[1]"))).build().perform();
  
     //Click on the buy icon of the 1st bag
     driver.findElement(By.xpath(" //ul[@class='results small']/li[1]/div[1]//div[2]")).click();
  
     // Wait For Page To Load
     driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  
     // Hover over the shopping bag icon present on the top navigatinal bar   
     Actions a3 = new Actions(driver);
     a3.moveToElement(driver.findElement(By.xpath("//a[@href='/checkout/cart']"))).build().perform();
  
     // click on the remove icon
     driver.findElement(By.xpath("//a[@data-hint='Remove item']")).click();
  
     //closing current driver window 
     driver.close();   
    }
}

Hope this helps the beginners.

Thanks for reading.

A small Tip for – How to take Screen Shot using Selenium WebDriver?

In the previous blog we had discussed in short , ” How to automate a browser !! “. As a beginner like me,  you will be very keen to take screen shot of a particular page.

Here is a simple script for taking screen shot of any URL. I have taken “http://www.flipkart.com/&#8221; as mu URL.

package login;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Screen_shot {

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

// Initialize WebDriver
WebDriver driver = new FirefoxDriver();
// Wait For Page To Load

driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
// Go to URL
driver.get("http://www.flipkart.com/");
// Maximize Window
driver.manage().window().maximize();
// Take ScreenShot
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\selenium\\screenshot1.png"), true);
// Close Driver
driver.quit();
}
}

Below are few points with images.

  • 13456
  • For the above image you have to Import this package only [  ‘FileUtlis’ (org.apache.commons.io) ]
  • After completion of the script, the PNG file will be stored in your given location. I have given [ “D:\\selenium\\screenshot1.png” ]. Here is the screen shot below.

File has been saved in the format i.e png as mentioned in the script.

  • File has been saved in the format i.e “png” as mentioned in the script. We can save the image in different file type like PNG, JPEG, GIF, BMP.

Hope this helps Beginners like me… 🙂

 

 

A small Java script using Selenium Webdriver.

In the previous post we had discussed about the installation of Java, and configuration of Eclipse with selenium WebDriver. Now here we will be creating a small Java script. All beginners will 1st want to open browser and to automate it. So here we will be doing that.

First of all we will write the scenario of what we will be doing here.Here we will Login to Gmail account and will automate the below scenarios.

  1. Open A firefox Browser.
  2. Navigate to the URL.
  3. Maximize the window.
  4. Enter the User Name and Password.
  5. Sign-In to the Gmail Account.
  6. Click on the Compose Button.
  7. Sign-Out from the gmail account.
  8. Close the browser.

Now we will automate the above scenario. In the previous post I had discussed about creating a Java Project, Package, Class. And how to import the JAR files into the project. Here also we have follow the same thing. For example, we will create a Project called “Gmail” , Package as “login”, Class as “Login1”. Now we will write the code as below.

package login;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Login1 {
public static void main(String[] args) {
// Create a new instance of the Firefox driver
WebDriver driver = new FirefoxDriver();
//  Wait For Page To Load
// Put a Implicit wait, this means that any search for elements on the page
could take the time the implicit wait is set for before throwing exception 
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Navigate to URL
driver.get("https://mail.google.com/");
// Maximize the window.
driver.manage().window().maximize();
// Enter UserName
driver.findElement(By.id("Email")).sendKeys(" YOUR USER NAME");
// Enter Password
driver.findElement(By.id("Passwd")).sendKeys("YOUR PASSWORD");
// Wait For Page To Load
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
// Click on 'Sign In' button
driver.findElement(By.id("signIn")).click();
//Click on Compose Mail.
driver.findElement(By.xpath("//div[@class='z0']/div")).click();
// Click on the image icon present in the top right navigational Bar
driver.findElement(By.xpath("//div[@class='gb_1 gb_3a gb_nc gb_e']/div/a")).click();
//Click on 'Logout' Button
driver.findElement(By.xpath("//*[@id='gb_71']")).click();
//Close the browser.
driver.close();
}
}
  • After writing this script you will see that some  RED lines under some element like this->

1

  • By Hovering over the Bulb symbol present in the left side, you can know which type of error it is.

2

  • You just need to hover the mouse pointer on that particular element or Click on that particular element and  press [ Ctrl+Space] on the key board. Many suggestions will be listed there and you have to select the appropriate package for that element. To know which Class belong to which Package, Click on http://selenium.googlecode.com/git/docs/api/java/index.html. See below for the images in details.

3

4

5

  • Now Run the script by Right click on the Class ->Run As -> Java Application.

OR

  • Click on the Run Icon present in the Top Navigational Bar.

6

Now you will see the browser will automatically open and will perform the desired task as mentioned above.

So in this Article we discussed about automating the Gmail Login and Sign-out functionality using WebDriver.

Hope this helps Beginners like me… 🙂