首页 > 解决方案 > 使用 RemoteWebDriver 截屏

问题描述

有没有办法获得带有标题的硒截图?我已经尝试了下面的代码,但屏幕截图没有标题。我有一个测试用例,需要单击一个链接并确保该操作必须带到一个新选项卡,因此作为证据,我必须附加捕获有两个选项卡。

public static void main (String args[]) throws IOException {
    DesiredCapabilities dc = new DesiredCapabilities();
    RemoteWebDriver driver;

    URL url = new URL("http://localhost:4444/wd/hub");
    dc.setCapability(CapabilityType.BROWSER_NAME, BrowserType.CHROME);
    dc.setCapability(CapabilityType.PLATFORM, "MAC");

    driver = new RemoteWebDriver(url, dc);
    driver.manage().window().maximize();
    driver.get("https://google.com");

    new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.name("q")));

    File getImage = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(getImage, new File("/Users/path/screenshot.jpg"));

    driver.quit();
}

当前结果 当前结果

预期结果 预期结果

标签: javaselenium

解决方案


正如@Ardesco 建议的那样,无法截取屏幕截图。

但是我认为您可以使用java.awt.Robot类来捕获屏幕。它获取当前屏幕的屏幕截图。

这是使用 java.awt 捕获屏幕截图的代码快照,

public void getScreenshot(int timeToWait) throws Exception {
    Rectangle rec = new Rectangle(
      Toolkit.getDefaultToolkit().getScreenSize());
    Robot robot = new Robot();
    BufferedImage img = robot.createScreenCapture(rectangle);
    
    ImageIO.write(img, "jpg", setupFileNamePath());
}

推荐阅读