Ankit_Add

Wednesday, September 23, 2015

How to handle javascript alerts, confirmation and prompts?

Generally JavaScript popups are generated by web application and hence they can be easily controlled by the browser.
Webdriver offers the ability to cope with javascript alerts using Alerts APIClick here to view Alert API Details
// Get a handle to the open alert, prompt or confirmation
Alert alert = driver.switchTo().alert();
Alert is an interface. There below are the methods that are used
//Will Click on OK button.
alert.accept();
// Will click on Cancel button.
alert.dismiss()
//will get the text which is present on th Alert.
alert.getText();
//Will pass the text to the prompt popup
alert.sendkeys();
//Is used to Authenticate by passing the credentials
alert.authenticateUsing(Credentials credentials)

Working with Alerts using Selenium Webdriver:

The below is the sample code for alerts, please copy and make an html file and pass it to the webdriver.
<html>
<head>
<title>Selenium Easy Alerts Sample </title>
</head>
<body>
<h2>Alert Box Example</h2>
<fieldset>
<legend>Alert Box</legend><p>Click the button to display an alert box.</p>
<button onclick="alertFunction()">Click on me</button>
<script>
function alertFunction()
{
alert("I am an example for alert box!");
}
</script>
</fieldset>
</body>
</html>

The below program will demonstrate you working on Alerts popup using above html file.
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class PopupsHandling {
 WebDriver driver=new FirefoxDriver();
 @Test
 public void ExampleForAlert() throws InterruptedException
 {
  driver.manage().window().maximize();
  driver.get("file:///C:/path/alerts.html");
  Thread.sleep(2000);
  driver.findElement(By.xpath("//button[@onclick='alertFunction()']")).click();
  Alert alert=driver.switchTo().alert();
  System.out.println(alert.getText());
  alert.accept();
 }
}

Working with Confirmation Popups

The below is the sample code for confirmation Popup, please copy and make an html file and pass it to the webdriver as below.
<html>
<head>
<title>Selenium Easy Confirm popup Sample </title>
</head>
<body>
<h2>Confirm Box Example</h2>
<fieldset>
<legend>Confirm Box</legend>
<p>Click the button to display a confirm box.</p>
<button onclick="confirmFunction()">Click on me</button>
<p id="confirmdemo"></p>
<script>
function confirmFunction()
{
var cb;
var c=confirm("I am an Example for Confirm Box.\n Press any button!");
if (c==true)
  {
  cb="You Clicked on OK!";
  }
else
  {
  cb="You Clicked on Cancel!";
  }
document.getElementById("confirmdemo").innerHTML=cb;
}
</script>
</fieldset>
</body>
</html>

The below program will demonstrate you working on Confirmation popup using above html file.
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class PopupsHandling {
 WebDriver driver=new FirefoxDriver();
 @Test
 public void ExampleForConfirmBox() throws InterruptedException
 {
  driver.manage().window().maximize();
  driver.get("file:///C:/path/confirmation.html");
  Thread.sleep(2000);
  driver.findElement(By.xpath("//button[@onclick='confirmFunction()']")).click();
  Alert alert=driver.switchTo().alert();
  System.out.println(alert.getText());
  alert.dismiss();
 }
}

Working with Prompt Popups.

In prompt, you can enter the text using webdriver sendkeys("text..")
The below is the sample code for prompt popup, please copy and make an html file and pass it to the webdriver as below.
<html>
<head>
<title>Selenium Easy Prompt popup Sample </title>
</head>
<body>
<h2>Prompt Box Example</h2>
<fieldset>
<legend>Prompt Box</legend>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="promptFunction()">Click on me</button>
<p id="promptdemo"></p>
<script>
function promptFunction()
{
var x;
var person=prompt("Please enter your name","Your name");
if (person!=null)
  {
  x="Hello " + person + "! Welcome to Selenium Easy..";
  document.getElementById("promptdemo").innerHTML=x;
  }
}
</script>
</fieldset>
</body>
</html>

The below program will demonstrate you working on prompt popup using above html file.
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class PopupsHandling {
 WebDriver driver=new FirefoxDriver();
 
 @Test
 public void ExampleForPromptBox() throws InterruptedException
 {
  driver.manage().window().maximize();
  driver.get("file:///C:/path/prompt.html");
  Thread.sleep(2000);
  driver.findElement(By.xpath("//button[@onclick='promptFunction()']")).click();
  Alert alert=driver.switchTo().alert();
  driver.switchTo().alert().sendKeys("Helllo");
  alert.accept();
  System.out.println(alert.getText());
 }
}

Use of Robot Class In Selenium WebDriver For Automation Purpose

During automation activity Selenium often find difficulty to find an object and perform actions which is related to mouse or keyboard type of activity. It is not easy to perform keyboard or mouse events using selenium commands. There are many specific scenarios where any selenium command is launched but actual event did not fired. This result that execution of test is stopped and it reports some error.


Here Java Robot Class come in picture. Using Robot Class we can simulate keyboard and mouse events in Selenium. This class is very easy to use with automation process. It can be easily integrate with current automation framework.

Robot Class is available under java.awt.package.


Methods in Robot Class can be effectively used to do the interaction with popups in Web Applications. Selenium does not provide support to handle browser pop-ups or the native operating system pop-ups. To handle these kind of pop-up, we need help of Robot Class. This is also used while we need to handle file upload and download activity using selenium webDriver.


The activity of file upload can also be handled using AutoIT. AutoIT is a tool that can automate the windows GUI. It generates an '.exe' file which is used by selenium script for file upload or download activity.


Some of the popular methods under Robot Class are:

.keyPress();

.mousePress();

.mouseMove();

.keyRelease();

.mouseRelease();




Here is an example to learn more about Robot Class


import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class UploadFileRobot {

 String URL = "application URL";
@Test
public void testUpload() throws InterruptedException
 {
 WebDriver  driver = new FirefoxDriver();
driver.get(URL);
WebElement element = driver.findElement(By.name("uploadfile"));
element.click();
uploadFile("path to the file");
Thread.sleep(2000);
 }

/**      * This method will set any parameter string to the system's clipboard.      */
public static void setClipboardData(String string) {
//StringSelection is a class that can be used for copy and paste operations.
    StringSelection stringSelection = new StringSelection(string);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
 }

public static void uploadFile(String fileLocation) {
        try {
        //Setting clipboard with file location
            setClipboardData(fileLocation);
            //native key strokes for CTRL, V and ENTER keys
            Robot robot = new Robot();

            robot.keyPress(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_V);
            robot.keyRelease(KeyEvent.VK_V);
            robot.keyRelease(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_ENTER);
        } catch (Exception exp) {
        exp.printStackTrace();
        }
    }
}

Monday, September 21, 2015

Locators in Selenium Webdriver

PSelenium webdriver uses 8 locators to find the elements on web page. The following are the list of object identifier or locators supported by selenium.

We have prioritized the list of locators to be used when scripting.

id - >

Select element with the specified @id attribute.

Name

Select first element with the specified @nameattribute.

Linktext

Select link (anchor tag) element which contains text matching the specified link text

Partial Linktext

Select link (anchor tag) element which contains text matching the specified partial link text

Tag Name

Locate Element using a Tag Name .

Class name

Locate Element using a Tag Name ..

Css

Select the element using css selectors. You can check here for Css examples and You can also refer W3C CSS Locatros

Xpath

Locate an element using an XPath expression.

Locating an Element By ID:
The most efficient way and preferred way to locate an element on a web page is By ID. ID will be the unique on web page which can be easily identified.
IDs are the safest and fastest locator option and should always be the first choice even when there are multiple choices, It is like an Employee Number or Account which will be unique.
Example 1:

<div id="toolbar">.....</div>

Example 2:

<input id="email" class="required" type="text"/>

We can write the scripts as

WebElement Ele = driver.findElement(By.id("toolbar"));

Unfortunately there are many cases where an element does not have a unique id (or the ids are dynamically generated and unpredictable like GWT). In these cases we need to choose an alternative locator strategy, however if possible we should ask development team of the web application to add few ids to a page specifically for (any) automation testing.

Locating an Element By Name:
When there is no Id to use, the next worth seeing if the desired element has a name attribute. But make sure there the name cannot be unique all the times. If there are multiple names, Selenium will always perform action on the first matching element
Example:

<input name="register" class="required" type="text"/> WebElement register= driver.findElement(By.name("register"));

Locating an Element By LinkText:
Finding an element with link text is very simple. But make sure, there is only one unique link on the web page. If there are multiple links with the same link text (such as repeated header and footer menu links), in such cases Selenium will perform action on the first matching element with link.

Locating an Element By Partial LinkText:
In the same way as LinkText, PartialLinkText also works in the same pattern.

User can provide partial link text to locate the element.

Locating an Element By TagName:
TagName can be used with Group elements like , Select and check-boxes / dropdowns.
below is the example code:

Select select = new Select(driver.findElement(By.tagName("select"))); select.selectByVisibleText("Nov"); or select.selectByValue("11");

Locating an Element By Class Name:
There may be multiple elements with the same name, if we just use findElementByClassName,m make sure it is only one. If not the you need to extend using the classname and its sub elements.
Example:

WebElement classtest =driver.findElement(By.className(“sample”));

CSS Selector:
CSS mainly used to provide style rules for the web pages and we can use for identifying one or more elements in the web page using css.
If you start using css selectors to identify elements, you will love the speed when compared with XPath. Check this for more details on Css selectors examples

We can you use Css Selectors to make sure scripts run with the same speed in IE browser. CSS selector is always the best possible way to locate complex elements in the page.

Example:

WebElement CheckElements = driver.findElements(By.cssSelector("input[id=email']"));

XPath Selector:
XPath is designed to allow the navigation of XML documents, with the purpose of selecting individual elements, attributes, or some other part of an XML document for specific processing

There are two types of xpath

1. Native Xpath, it is like directing the xpath to go in direct way. like
Example:
html/head/body/table/tr/td

Here the advantage of specifying native path is, finding an element is very easy as we are mention the direct path. But if there is any change in the path (if some thing has been added/removed) then that xpath will break.

2. Relative Xpath.
In relative xpath we will provide the relative path, it is like we will tell the xpath to find an element by telling the path in between.
Advantage here is, if at all there is any change in the html that works fine, until unless that particular path has changed. Finding address will be quite difficult as it need to check each and every node to find that path.
Example:
//table/tr/td

Example Syntax to work with Image

    xpath=//img[@alt='image alt text goes here']

Example syntax to work with table

    xpath=//table[@id='table1']//tr[4]/td[2]     xpath=(//table[@class='nice'])//th[text()='headertext']/

Example syntax to work with anchor tag

    xpath=//a[contains(@href,'href goes here')]     xpath=//a[contains(@href,'#id1')]/@class

Example syntax to work with input tags

    xpath=//input[@name='name2' and @value='yes']

We will take and sample XML document and we will explain different methods available to locate an element using Xpath