如果代码在localhost
的服务器上执行,不到一秒钟(大约400-500ms),则截图速度非常快:
private RemoteWebDriver driver;
private DesiredCapabilities dc = new DesiredCapabilities();
@Before
public void setUp() throws MalformedURLException {
....
....
dc.setCapability(CapabilityType.BROWSER_NAME, BrowserType.CHROME);
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), dc);
}
@Test
public void test() throws InterruptedException, IOException {
driver.get("https://google.com");
driver.findElement(By.name("q")).sendKeys("automation test");
long before = System.currentTimeMillis();
//here is the problem
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
long after = System.currentTimeMillis();
System.out.println(after-before);
FileUtils.copyFile(srcFile, new File("/Users/name/localpath/test.png"));
}
但是,如果将目标服务器更改为安装了Selenium服务器的公共IP
,则截取屏幕截图的速度会较慢(约5秒)。也许这可能是由于客户端和服务器之间的距离,所以一定有区别。
是否可以减少屏幕截图花费时间?我正在考虑降低图像分辨率,但如何调整?
获取较小尺寸屏幕截图(除了使用各种文件格式)的一种方法是更改屏幕截图的大小:您可以拍摄您特别感兴趣的 Web 元素(或页面区域)的屏幕截图。
尝试以下操作(您将需要使用BufferedImage类):
@Test
public void test() throws InterruptedException, IOException {
driver.get("https://google.com");
driver.findElement(By.name("q")).sendKeys("automation test");
long before = System.currentTimeMillis();
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Point p = element.getLocation();
int width = element.getSize().getWidth();
int height = element.getSize().getHeight();
BufferedImage img = ImageIO.read(scrFile);
BufferedImage elementScreenshot = img.getSubimage(p.getX(), p.getY(), width, height);
//NOTE: the line above will crop the full page screenshot to element dimensions, change width and height if you wish to crop to region
Image.write(elementScreenshot, "png", scrFile);
FileUtils.copyFile(srcFile, new File("/Users/name/localpath/test.png"));
long after = System.currentTimeMillis();
System.out.println(after-before);
}
问题很可能是通过网络传输文件。它也可能在文件的创建中。
我建议尝试使用 Base64 输出,看看这是否会减少传输时间:
String screenshotAsBase64String = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);