Saturday, 20 December 2014

Screenshot - specific element

Let's see how a screenshot of a specfic element can be taken.

Scenario :

Launch www.babyoye.com and capture screenshot of the element "READ MORE" available at the bottom of the page and save it in .jpg format .


This is how it's done,

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class ScrDemo3 {

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

System.setProperty("webdriver.ie.driver", "D:\\IEDriverServer.exe");

WebDriver driver = new InternetExplorerDriver();

driver.navigate().to("http://www.babyoye.com/c/Cribs-&-Cradles");

WebElement we = driver.findElement(By.linkText("READ MORE"));

File srcFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);

BufferedImage img = ImageIO.read(srcFile);

Dimension d = we.getSize();

int width = d.getWidth();

int height = d.getHeight();

Point p = we.getLocation();

int x = p.getX();

int y = p.getY();

BufferedImage eleScreenshot = img.getSubimage(x, y, width, height);

ImageIO.write(eleScreenshot, "jpg", srcFile);

FileUtils.copyFile(srcFile, new File(System.getProperty("user.dir")
+ "\\Screenshot\\ElementScr.jpg"));

System.out.println("Screenshot captured");

driver.quit();
}

}

The screenshot taken is :



Pay It Forward...

Lots of energy ..

DR

Take screenshot - and mark an element

In this post , let's see how to take screenshot of an entire page and mark a particular field , with a rectangular blue mark.


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MarkScreenshotDemo {

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

WebDriver driver = new FirefoxDriver();

driver.get("http://www.babyoye.com/c/Cribs-&-Cradles");

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);

BufferedImage image = ImageIO.read(scrFile);

Graphics2D graphics = image.createGraphics();

  //This is the search box on top
WebElement we = driver.findElement(By.name("q"));

  //To get the position and dimension of the element
int x = we.getLocation().getX();

int y = we.getLocation().getY();

int width = we.getSize().getWidth();

int height = we.getSize().getHeight();

System.out.println("Drawing rectangle at " + x + ", " + y + ", "
+ width + ", " + height);

  //The colour for the rectangle which is to be drawn around the element
graphics.setColor(Color.BLUE);

  //Thickness of each side of the rectangle
graphics.setStroke(new BasicStroke(10.0f));

  //To draw the rectangle around the element
graphics.drawRect(x, y, width, height);

  //Path to save the screenshot
ImageIO.write(image, "png", new File(System.getProperty("user.dir"),
"\\Screenshot\\" + "babyoye.png"));

System.out.println("Screenshot taken");

driver.quit();

}

}

This is the screenshot taken :

In this screenshot,the search box on top has been marked with a rectangle as per the colour and thickness mentioned in the program.



Pay It Forward

DR

Screenshot - entire page

Let's see how one can take screenshot of the entire page .


import java.io.File;
import java.io.IOException;
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.ie.InternetExplorerDriver;

public class ScrDemo1 {

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

System.setProperty("webdriver.ie.driver", "D:\\IEDriverServer.exe");

WebDriver driver = new InternetExplorerDriver();

driver.navigate()
.to("http://www.toolsqa.com/automation-practice-form/");

            //TakesScreenshot is an interface and we are casting our driver instance to it

File srcFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);

            //The path where the screenshot should be saved

FileUtils.copyFile(srcFile, new File(
"D:\\Screenshot\\ScrDemo1.png"));

System.out.println("Screenshot captured");

driver.quit();

}

}

This is the screenshot taken :

ScrDemo1 screenshot


Pay It Forward

DR

Friday, 19 December 2014

Instantiating webdriver


Webdriver is the name of the interface. 

FirefoxDriver, OperaDriver,SafariDriver,ChromeDriver,InternetExplorerDriver are all classes which can implement Webdriver interface.

Here's how one can instantiate webdriver for the browsers supported by selenium webdriver.

FireFox 
WebDriver driver = new FirefoxDriver();

Opera
WebDriver driver = new OperaDriver();

Safari
WebDriver driver = new SafariDriver();

Internet Explorer
I downloaded IEDriver 32 bit version for windows from the link mentioned below, and I pasted the downloaded file into my machine's D drive.

http://selenium-release.storage.googleapis.com/index.html?path=2.44/ 


Secondly, we need to do the following 

In IE browser window, go to Internet Options and under Security tab,for each of the zones, Internet,Local intranet,Trusted sites,Restricted sites,either check or uncheck, Enable Protected Mode checkbox


If protected mode is not set to the same in all regions, then the following exception occurs :


Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information)

So once this is done, we need to specify the path to the IE driver binary in our code as mentioned below,

System.setProperty("webdriver.ie.driver","D:\\IEDriverServer.exe");

WebDriver driver = new InternetExplorerDriver();

Tuesday, 16 December 2014

How to perform a series of actions using Keys.chord?

Using Keys.chord, we can simulate a series of actions.It takes a sequence of Keys.XXXX or strings, appends each of the values to a string, and adds the chord termination key (Keys.NULL) and returns the resultant string. 

Note: When the low-level webdriver key handlers see Keys.NULL, active modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event

Let's see how we can tab from one element to another and perform some action in the new element.


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;

public class KeysChordDemo1 {

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

WebDriver driver = new FirefoxDriver();

driver.navigate()
.to("http://www.toolsqa.com/automation-practice-form/");

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

driver.manage().window().maximize();

WebElement we = driver.findElement(By.name("firstname"));

String chords = Keys.chord(Keys.SHIFT, "Senthil")

//Tab to last name field
+ Keys.TAB

//Enter last name in caps . Use Keys.NULL to release SHIFT key
+ Keys.SHIFT + "kumaran" + Keys.NULL

//Tab to gender radio button
+ Keys.TAB

//Tab to Years of Experience,control will be in radio button 1
+ Keys.TAB

//Radio button 2 is selected
+ Keys.ARROW_RIGHT

//Radio button 3  is selected
+ Keys.ARROW_RIGHT

//Radio button 4  is selected
+ Keys.ARROW_RIGHT

//Radio button 5  is selected
+ Keys.ARROW_RIGHT

//Radio button 6  is selected
+ Keys.ARROW_RIGHT

//Radio button 7 is finally selected
+ Keys.ARROW_RIGHT

//Tab to date field and enter date
+ Keys.TAB + "27-05-2014"

//Tab to Profession checkbox, control is in first checkbox
+ Keys.TAB

//Tab to second checkbox 
+ Keys.TAB 

//And check it 
+ Keys.SPACE;

we.sendKeys(chords);


Thread.sleep(3000l);

driver.quit();

}

}


Pay It Forward..

DR

Monday, 15 December 2014

Toggling between tabs

Let's deal with toggling between tabs .Here there will be only one window handle for any number of tabs that get opened in that session, unlike the multiple window handles that are present when number of windows are opened.

Here's the sample program,

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;

public class SwitchTabsDemo {

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

// This page will be tab1 in this scenario
driver.navigate()
.to("http://www.toolsqa.com/automation-practice-form/");

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

driver.manage().window().maximize();

// Finding username webelement in tab1
WebElement we = driver.findElement(By.name("firstname"));

// Both tabs will have the same window handle in this case
String han = driver.getWindowHandle();

// To open a new tab
we.sendKeys(Keys.chord(Keys.CONTROL, "t"));

// Launch another url in the new tab, tab2
driver.navigate().to("http://www.google.com");

// Locating the search box
WebElement we2 = driver.findElement(By.id("gbqfq"));

// Sending text to search box element
we2.sendKeys("sachin");

// Shifting control back to tab1
we2.sendKeys(Keys.chord(Keys.CONTROL, "\t"));

// Switching to first tab using handle
driver.switchTo().window(han);

// Sending text to user name text box in tab1
we.sendKeys("admin");

Thread.sleep(4000l);

// Shifting control to tab2
we.sendKeys(Keys.chord(Keys.CONTROL, "\t"));

// Switching to tab2 using handle
driver.switchTo().window(han);

// Both driver.close() and driver.quit() will just do the same task,
// driver instance gets killed
driver.quit();

}

}

Pay It Forward

DR

Toggling between windows


Let me tell you upfront , using Thread.sleep is not good at all, when you run a bunch of test cases.It will slow down the tests and hence it  is to be avoided. However, I have used it in my example here, I shall substitute with better wait options sooner .

So here goes the code for toggling between windows.


import java.util.Iterator;
import java.util.Set;
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 SwitchWindowsDemo {

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

WebDriver driver = new FirefoxDriver();

driver.navigate()
.to("http://www.toolsqa.com/automation-practice-form/");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// This is the parent window

driver.findElement(By.name("firstname")).sendKeys("parent window");

// Element on which to right click(Partial Link Test)

WebElement we = driver.findElement(By
.xpath("//a[contains(@title,'Form')]"));

Actions act = new Actions(driver);

// Right click,and click on second option from menu,which will open new
// window which is the child window

act.contextClick(we).sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build()
.perform();

Thread.sleep(2000l);

Set<String> st = driver.getWindowHandles();

Iterator<String> itr = st.iterator();

String parentHandle = itr.next();

String childHandle = itr.next();

  //Switching control to child window using its handle

driver.switchTo().window(childHandle);

// Control has been passed to child window, performing some action in
// the child window

driver.findElement(By.name("firstname")).sendKeys("child window");

Thread.sleep(2000l);

// This will close only the child window
//If we use driver.quit() instead, then the session gets closed right away

driver.quit();

// Shifting control back to parent window

driver.switchTo().window(parentHandle);

driver.findElement(By.name("lastname")).sendKeys(
"back in parent window");

Thread.sleep(1000l);

// This will close the session

driver.quit();

}

}



Pay It Forward

DR

Right Click using Actions class

Here's a basic program for performing right click using Actions class. The code will right click on a specified link, scroll to the second menu item and select it. In this case, the menu item is "Open Link In New Window" . However, this sample does not explain about switching windows, focus remains on right click option using webdriver.

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 ContextClickDemo {

public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();

driver.navigate()
.to("http://www.toolsqa.com/automation-practice-form/");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Element on which to right click

WebElement we = driver.findElement(By
.xpath("//a[contains(@title,'Form')]"));

Actions act = new Actions(driver);

// Right click,and select second option from menu which will open a new window

act.contextClick(we).sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build().perform();
 //Instead of sendKeys(Keys.RETURN), we can also use sendKeys(Keys.ENTER)

driver.quit();

}

}


Check my next post "Toggling between windows"  for switching windows :)

Pay It Forward

DR

Saturday, 6 December 2014

Sending capital text into a textbox using Robot class

The aim is to shift focus into a textbox and to send capital text using Robot class. Yes, there are other ways of doing this too apart from using Robot class, but I just wanted to give this a try and here's how it's done,

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;

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


public class RobotDemoKeyPress {

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

WebDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

driver.get("http://www.google.com");

//To get the focus into the search box
driver.findElement(By.id("gbqfq")).sendKeys("");

Robot robot = new Robot();

//To send the text in Caps
robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
robot.keyPress(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_C);
robot.keyPress(KeyEvent.VK_H);
robot.keyRelease(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_I);
robot.keyRelease(KeyEvent.VK_I);
robot.keyPress(KeyEvent.VK_N);
robot.keyRelease(KeyEvent.VK_N);
robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);

}

}

Pay it forward..

DR

Working with OperaDriver


I have been trying to write WebDriver tests for Opera browser. 

So, I had downloaded the latest versions of Opera , version 26 and selenium-server-standalone jar, 2.44.0.

From what I read from Selenium's official website, I understood that it could be created like the normal FirefoxDriver.

I wrote a simple test,

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import com.opera.core.systems.OperaDriver;

public class OperaDemo {


 public static void main(String[] args)  {


WebDriver driver = new OperaDriver();


driver.manage().window().maximize();


driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 
driver.get("http://www.toolsqa.com/automation-practice-form/");

  driver.quit();

}

}


I was hoping that it would execute right away,as it's such a simple piece of code.. No, it did not :D:D

Exception occured :D

Exception in thread "main" org.openqa.selenium.WebDriverException: org.openqa.selenium.WebDriverException: Runner threw exception on construction Build info: version: '2.44.0' Driver info: driver.version: OperaDriver

Upon checking further, I got to know that,as of now there is support for OperaDriver  only until Opera version 12.X or less from the link


So, I downloaded an older version of Opera , version 12.16 and ran the same test again.

 It wasn't successful still, because of this line of code which is not supported by OperaDriver yet. 

driver.manage().window().maximize();

I removed this line of code, and only then did the application launch.. FINALLY!! 

I hope this helps. If it does , pay it forward...


Lots of energy ..

DR



















Thursday, 4 December 2014

How to handle windows popup and upload file ?


Let us see the scenario of file upload which invokes the windows based popup,on clicking the browse button or the 'Add file' button.

The first thing people immediately suggest is to use AutoIt.

I have been looking for other possible ways and this worked well for me,

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;


 public class UploadDemoWeTransfer {

public static void main(String[] args) throws AWTException, InterruptedException {

WebDriver driver = new FirefoxDriver();

driver.navigate().to("https://www.wetransfer.com/");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);

driver.findElement(By.xpath("//*[@id='takeover-skip']")).click();
driver.findElement(By.xpath("//*[@id='accepting']")).click();

driver.findElement(By.xpath("//*[@id='uploader_field']")).click();

WebElement element = driver.findElement(By
.xpath("//*[@id='uploader_field']"));
element.click();

StringSelection ss = new StringSelection(
"C:\\Users\\devatha\\Desktop\\New folder\\note.jpg");

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);


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);
    
    
   new FluentWait<WebDriver>(driver)
                .withTimeout(25, TimeUnit.SECONDS)
                .pollingEvery(5,TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class)
                .until(ExpectedConditions.textToBePresentInElement(By.id("add-file"), "Add more files"));

driver.findElement(By.xpath("//*[@id='add-recipient']")).click();
driver.findElement(By.xpath("//*[@id='to']")).sendKeys(
driver.findElement(By.xpath("//*[@id='add-sender']")).click();
driver.findElement(By.xpath("//*[@id='from']")).sendKeys(
driver.findElement(By.xpath("//*[@id='transfer']")).click();

}

}



Hope this helps. If it does, PAY IT FORWARD .. 



Lots of Energy,


DR