是否可以使用Selenium WebDriver进行截图?

(注:不含硒遥控器)


当前回答

C#

public static void TakeScreenshot(IWebDriver driver, String filename)
{
    // Take a screenshot and save it to filename
    Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
    screenshot.SaveAsFile(filename, ImageFormat.Png);
}

其他回答

Java

这里似乎没有-在Java中截取一个特定元素的截图:

public void takeScreenshotElement(WebElement element) throws IOException {
    WrapsDriver wrapsDriver = (WrapsDriver) element;
    File screenshot = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
    Rectangle rectangle = new Rectangle(element.getSize().width, element.getSize().height);
    Point location = element.getLocation();
    BufferedImage bufferedImage = ImageIO.read(screenshot);
    BufferedImage destImage = bufferedImage.getSubimage(location.x, location.y, rectangle.width, rectangle.height);
    ImageIO.write(destImage, "png", screenshot);
    File file = new File("//path//to");
    FileUtils.copyFile(screenshot, file);
}

是的,可以使用Selenium WebDriver对网页进行快照。

WebDriver API提供的getScreenshotAs()方法为我们做了这项工作。

语法:getScreenshotAs(OutputType<X> target)

返回类型:X

参数:target—查看OutputType提供的选项

适用性:不特定于任何DOM元素

例子:

    TakesScreenshot screenshot = (TakesScreenshot) driver;
    File file = screenshot.getScreenshotAs(OutputType.FILE);

有关详细信息,请参阅下面的工作代码片段。

    public class TakeScreenShotDemo {

        public static void main(String[] args) {
            WebDriver driver = new FirefoxDriver();
            driver.manage().window().maximize();
            driver.get(“http: //www.google.com”);

            TakesScreenshot screenshot = (TakesScreenshot) driver;

            File file = screenshot.getScreenshotAs(OutputType.FILE);

            // Creating a destination file
            File destination = new File(“newFilePath(e.g.: C: \\Folder\\ Desktop\\ snapshot.png)”);
            try {
                FileUtils.copyFile(file, destination);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

访问Snapshot using WebDriver获取更多详细信息。

你可以使用Webdriverclass对象创建一个webdriver支持的selenium对象,然后你可以截屏。

C# (Ranorex API)

public static void ClickButton()
{
    try
    {
        // code
    }
    catch (Exception e)
    {
        TestReport.Setup(ReportLevel.Debug, "myReport.rxlog", true);
        Report.Screenshot();
        throw (e);
    }
}

Java (Robot Framework)

我使用这种方法进行截图。

void takeScreenShotMethod(){
    try{
        Thread.sleep(10000)
        BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIO.write(image, "jpg", new File("./target/surefire-reports/screenshot.jpg"));
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

你可以在任何需要的地方使用这种方法。