java - 减少在 selenium 上的截图时间

标签 java selenium selenium-webdriver remotewebdriver takesscreenshot

如果代码在 的服务器上执行,则截屏非常快。 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/

相关文章:

java - 有没有更好的方法来检查子节点的类型并相应地返回?

javascript - Selenium Webdriver 是可检测的

javascript - 无法在 html 代码中找到表单 - 使用 Python 和 Selenium 进行 Web 抓取

selenium - WebDriver - 向浏览器发送 key 在 Firefox 中不起作用?

javascript - 如何使用 selenium webdriver 提取 <nobr> 中的动态文本?

node.js - 升级到 Protractor 4.0.9 后为 "Unable to connect to renderer"。测试不会运行。关于为什么的任何想法?

java - 阿皮姆 : Is there a way to automate an app without having IPA?

java - 交换数组中的元素

java - 在任何地方传递 `Context` 似乎都很困惑 - 创建类来处理与上下文的不同交互?

java - Selenium 3.7.1(Java)和 ChromeDriver 2.33.5