如何使用Selenium WebDriver截取屏幕截图

时间:2014-03-21 07:00:39

标签: java selenium selenium-webdriver

目前正致力于 Selenium WebDriver,Java TestNG 框架工作。

我用 Java 编写的代码。

如果我的Java代码是布尔值,可以截取屏幕截图

public boolean test()throws Exception  {}

有人可以建议我如何拍摄截图吗?

我尝试了这一步,但显示错误:

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

此行中的错误显示为copyFile The method copyFile(File, File) is undefined for the type FileUtils

 FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

7 个答案:

答案 0 :(得分:2)

import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.apache.commons.io.FileUtils;


public  class Test {
public void screenShot() {
    // driver is your WebDriver
    File screenshot = ((TakesScreenshot) driver)
                            .getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshot, new File(fileName));

}

}

答案 1 :(得分:0)

以下是此示例程序:

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

答案 2 :(得分:0)

你可以做的另一件事,而不是截图,以确保页面看起来像你想要的那样:

  1.  Use WebElement.getLocation() to get the coordinates of the element 
        or page section.
  2.  Use WebElement.getSize() to get the dimensions of that element 
        or page section.
  3.  Use WebElement.getText() to verify contents of that element or section.

答案 3 :(得分:0)

如果我们有Firefox Driver对象,那么

    FirefoxDriver Driver = new FirefoxDriver();
    Driver.get("http://facebook.com/");
    File ScrFile=Driver.getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(ScrFile, new File("D://img.jpg"));

答案 4 :(得分:0)

here下载shutterbug JAR文件。

public void takeSnapShot(String i) throws Exception {
/* Function : This function is used to take snapshot. It will take snapshot of entire page.
Function Call : takeSnapShot("Screen_name");*/
Shutterbug.shootPage(browser, ScrollStrategy.BOTH_DIRECTIONS).save(Path + i);
}

答案 5 :(得分:0)

//将Web驱动程序对象转换为TakeScreenshot

TakesScreenshot scrst =(((TakesScreenshot)webdriver);

        //Call getScreenshotAs method to create an image file

         File SrcFile=scrst.getScreenshotAs(OutputType.FILE);

        //Move image file to the new destination

         File DestFile=new File(fileWithPath);

        //Copy file at the destination

        FileUtils.copyFile(SrcFile, DestFile);

答案 6 :(得分:0)

    TakesScreenshot scrShot = ((TakesScreenshot)webdriver);

    File SrcFile = scrShot.getScreenshotAs(OutputType.FILE);

    File DestFile = new File(fileWithPath);

    FileUtils.copyFile(SrcFile, DestFile);
}