Friday, 8 May 2015

Selenium:How to capture screen shot using seleniumm webdriver

package New;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;

public class Screenshots {
    WebDriver driver;

    @Test
    public void screesnshot() throws IOException, InterruptedException {
        driver.get("http://www.bing.com/");
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        // search
        driver.findElement(By.id("sb_form_q")).sendKeys("webdriver");
        // Thread.sleep(5000);
        driver.findElement(By.name("go")).click();

        WebElement clicker = driver.findElement(By
                .xpath(".//*[@id='b_results']/li[1]/h2/a"));
        Actions a = new Actions(driver);

        a.contextClick(clicker).sendKeys(Keys.ARROW_DOWN)
                .sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.RETURN).build()
                .perform();

        //giving location where to save screen shots
        String screeLocation = "C:\\Users\\Ramesh\\Desktop\\Aldo_Scripts\\Results\\screenshots\\";

        // captures screen
        File sreen = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);

        FileUtils.copyFile(
                sreen,
                new File(screeLocation + new Date().getHours() + "_"
                        + System.nanoTime() + ".png"));
        Thread.sleep(9000);
    }

    @BeforeClass
    public void beforeClass() {
        driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @AfterClass
    public void afterClass() {
        driver.quit();
    }

}

No comments:

Post a Comment