4

如果代码在服务器上执行,截图速度非常快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 秒)。也许这可能是由于客户端和服务器之间的距离,所以一定有区别。

是否可以减少截屏时间?我正在考虑降低图像分辨率,但如何调整呢?

4

2 回答 2

1

问题很可能是通过网络传输文件。IT 也可能在创建文件。

我建议尝试使用 Base64 输出,看看是否会减少传输时间:

String screenshotAsBase64String = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);
        
于 2020-12-05T20:14:06.990 回答
1

裁剪屏幕截图

获得更小的屏幕截图(除了使用各种文件格式)的一种方法是更改​​屏幕截图的大小:您可以截取您特别感兴趣的 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);
}
于 2020-12-03T09:16:04.863 回答