如果代码在 的服务器上执行,则截屏非常快。 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"));
}
但是如果目标服务器改为 public ip
安装了 Selenium 服务器,截屏会更慢(大约 5 秒)。也许这可能是由于客户端和服务器之间的距离,所以必须有所不同。是否可以减少屏幕截图的时间?我正在考虑降低图像分辨率,但我该如何调整呢?
最佳答案
裁剪屏幕截图
获得较小尺寸屏幕截图(而不是使用各种文件格式)的一种方法是更改屏幕截图的大小:您可以截取您特别感兴趣的网络元素(或页面区域)的屏幕截图。
尝试以下操作(您需要使用 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);
}
关于java - 减少在 selenium 上的截图时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65068608/