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 extract all links of 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 ExtractAllinks {

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://www.google.com&#8221;);

// In HTML, the links start with anchor “a” tag. so we can find find the elements starting with “a”.
java.util.List<WebElement> links1 = driver.findElements(By.tagName(“a”));
// Number of links present.
int nsize = links1.size();
System.out.println(“Number of links are –  ” + nsize);

for(int i=0; i< nsize; i++){
String text= links1.get(i).getText();
System.out.println(“Name of the link ” + i + ” – “+ text);
}

}

}

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 🙂

 

 

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.

Locating Elements on a web page

In my previous article I have written about Browsers Commands.

In a webpage there are different Web Elements present like Buttons, Inputs boxes, Links, Drop-down lists, Check-boxes, Radio buttons, Plain texts and other items.To interact with the above elements we need to locate them first. Selenium provides number of Locators to locate the elements.

The different types of locator are-

  • Locating By Id
  • Locating By Name
  • Locating By Class Name
  • Locating by Tag Name
  • Locating Hyperlinks by LinkText
  • Locating By Xpath
  • Locating By CSS

Locating elements on a webpage can be done using the findElement and findElements method.

findElement() –

  • This method will find the first element within the current page using the given “locating mechanism”.
  • It returns a single WebElement.
  • If “findElement” will not find any element within the page then it will throw NoSuchElementException.
  • Syntax – WebElement findElement(By. “ANY LOCATOR”);

findElements() method –

  • This method is use to find multiple element on webpage.
  • It returns a list of WebElements.
  • If no element is not found, it will return empty List of WebElement and no exception will be thrown.
  • Syntax – java.util.List<WebElement> findElements(By. “ANY LOCATOR”);

Now we have to install 2 plugins[Firebug, Firepath] so as to integrate it with Firefox as it will help us to inspect the element and to generate Xpath.

  • First Add Firebug to the Firefox. Click this link to Add.
  • After integrating the FireBug with Firefox add FirePath from this Link.

Now Open the Firebug by Pressing F12 on your keyboard. Then click on the inspect Element icon in the Firebug. It will show the html view of that particular element. See below for the image.

1

Now Lets discuss the Syntax for each Locator.

  • Locating Element By.Id()-

By.Id  – This helps to find the element using the Id.

Syntax-

driver.findElement(By.id(“id of the element”));

  • Locating Element By.Name() –

By.Name – This helps to locate the element by the value of the “name” attribute.

Syntax-

driver.findElement(By.name(“name of the element”));

  • Locating Element By.tagName() –

By.tagName – This helps to locate the web element based on the HTML tag.

Syntax-

driver.findElement(By.tagName(“tagname”));

  • Locating Element By.linkText() –

By.linkText – This helps to locate the element by text displayed on link.

Syntax-

 driver.findElement(By.linkText(“link text”));

  • Locating ElementBy.partiallinkText: It is same as Link text. Only difference is here it helps to locate the  link element which is having partial matching text.

Syntax-

driver.findElement(By.partiallinkText(“partial text”));

  • By.ClassName :- This helps to locate the web element based on the“class” attribute.

Syntax-

driver.findElement(By.className(“Name of the class”));

  • By.xpath:- This helps to locate elements via xpath.

Syntax-

driver.findElement(By.xpath(“xpath of the element”));

  • By.cssSelector:- This helps to locate element using the CSSSelector.

Syntax-

driver.findElement(By.cssSelector(“selector”));

So, in this post we discussed about the different ways of Locating Elements on a web page. Hope this article will help you 🙂

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… 🙂