任何人都可以解释Selenium中的截图吗? [英] Can any one explain Screenshot in Selenium?

查看:182
本文介绍了任何人都可以解释Selenium中的截图吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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"));

可以告诉我

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

getScreenShotAs TakesScreenshot 界面中的方法......

getScreenShotAs is the method in the TakesScreenshot Interface......

(TakesScreenshot)驱动程序,它指的是什么?你能解释一下吗?

(TakesScreenshot)driver, What it refers to??? can you please explain little bit?

推荐答案

WebDriver 界面不包含 getScreenshotAs()方法,因为有可能让webdriver无法截取屏幕截图 - 例如内存驱动程序根本不呈现页面,例如 HtmlUnitDriver

The WebDriver interface does not contain the getScreenshotAs() method, because it is possible to have a webdriver unable of taking screenshots - for example the in-memory drivers that don't render the page at all, like HtmlUnitDriver.

为了获得该方法,驱动程序必须实现 TakesScreenshot 界面,这使得它能够......好...截取屏幕截图。

In order to have the method, the driver must implement the TakesScreenshot interface which makes it capable to ... well ... take screenshots.

因此,您必须以某种方式告诉程序您想截取屏幕截图,并且您绝对相信您可以这样做。这就是(TakesScreenshot)驱动程序部分的用途。在Java中,它被称为投射,它实际上转换为我知道这个 driver 实例可以截取屏幕截图,请将其投射到 TakesScreenshot 类型。

Therefore, you must tell the program somehow that you want to take a screenshot and that you are absolutely sure you can do so. That's what the (TakesScreenshot)driver part is for. In Java, it's called casting and it literally translates to "I know that this driver instance is able to take a screenshot, please cast it to TakesScreenshot type."

如果您的演员成功,一切都很好,驱动程序对象将在运行时转换为 TakesScreenshot 。但是,如果您的演员表失败,您将获得 运行时的ClassCastExcepion

If your cast succeeds, everything is fine and the driver object will be cast at run-time to an instance of TakesScreenshot. If your cast fails, however, you'll get a ClassCastExcepion at run-time.

一些例子:

// We already know this is ok, because FirefoxDriver implements (IS-A) TakesScreenshot.
WebDriver driver = new FirefoxDriver();
TakesScreenshot screenshottingDriver = (TakesScreenshot)driver;

// This will fail at run-time, because HtmlUnitDriver does not implement TakesScreenshot;
WebDriver driver = new HtmlUnitDriver();
TakesScreenshot screenshottingDriver = (TakesScreenshot)driver;

// You can use the `instanceof` operator to check:
if (driver instanceof TakesScreenshot) {
    // we can be sure we can take screenshots, the cast will be safe
    ((TakesScreenshot)driver).getScreenshotAs(...);
}

这篇关于任何人都可以解释Selenium中的截图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆