[英]Reducing screenshot taking time on selenium
如果代码在localhost
的服务器上执行,截图速度非常快,不到一秒(大约 400-500 毫秒):
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 服务器的public ip
,则截屏会更慢(大约 5 秒)。 也许这可能是由于客户端和服务器之间的距离,所以一定有区别。
是否可以减少截屏时间? 我正在考虑降低图像分辨率,但如何调整呢?
获得更小尺寸屏幕截图(除了使用各种文件格式)的一种方法是更改屏幕截图的大小:您可以截取您特别感兴趣的 web 元素(或页面区域)的屏幕截图。
尝试以下操作(您将需要使用BufferedImage class ):
@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);
}
问题很可能是通过网络传输文件。 IT 也可能在创建文件。
我建议尝试使用 Base64 output 看看这是否会减少传输时间:
String screenshotAsBase64String = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.