Wednesday, October 29, 2014

Chapter 19 - Scripting using Webdriver

Scripting using Webdriver

Let us understand how to work with webdriver. For demo purposes, we would use http://www.calculator.net/. We will perform a "percent Calculator" which is located under "Math Calculator". We have already downloaded the required webdriver JAR's. Refer Environmental chapter for details.
Step 1 : Launch "Eclipse" from the Extracted Eclipse Folder.
Selenium IDE 75
Step 2 : Select the Workspace by clicking on 'Browse' Button.
Selenium IDE 76
Step 3 : Now Create 'New Project' from 'File' Menu.
Selenium IDE 53
Step 4 : Enter the Project Name and Click 'Next'.
Selenium IDE 77
Step 5 : Goto Libraries Tab and select all the JAR's that we have dowonloaded(Refer Environment Set up Chapter). Add reference to all JAR's of Selenium Webdriver Library folder and also selenium-java-2.42.2.jar and selenium-java-2.42.2-srcs.jar
Selenium IDE 78
Step 6 : The Package is created as shown below.
Selenium IDE 79
Step 7 : Now let us create a 'Class' by performing right click on package and select 'New' >> 'Class'
Selenium IDE 82
Step 8 : Now name the class and make it as main Function
Selenium IDE 80
Step 9 : The class outline is shown as below.
Selenium IDE 81
Step 10 : Now it is time to code. The below Script is easier to understand as it explains clearly step by step in the embedded comments. Please take a look at "Locators" chapter to understand how to capture object properties.
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class webdriverdemo
{
  public static void main(String[] args)
  {
 WebDriver driver = new FirefoxDriver();

    //Puts a Implicit wait, Will wait for 10 seconds before throwing exception
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    //Launch website
 driver.navigate().to("http://www.calculator.net/");
 
 //Maximize the browser
 driver.manage().window().maximize();

    // Click on Math Calculators
 driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();
  
    // Click on Percent Calculators
 driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click();

 // Enter value 10 in the first number of the percent Calculator
    driver.findElement(By.id("cpar1")).sendKeys("10");

    // Enter value 50 in the second number of the percent Calculator
    driver.findElement(By.id("cpar2")).sendKeys("50");
    
    // Click Calculate Button
    driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr/td[2]/input")).click();

    // Get the Result Text based on its xpath
    String result = driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b")).getText();
    
 //Print a Log In message to the screen
    System.out.println(" The Result is " + result);
    
 //Close the Browser.
    driver.close();    
  }
}
Step 11 : The Output of the above script would be printed in Console.
Selenium IDE 83

No comments: