2

我正在尝试在 selenium 运行时截取网页的屏幕截图。我为此目的使用以下代码

WebDriver augmentedDriver = new Augmenter().augment(seleniumDriver);
            File scrFile = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);

现在它很好地满足了我的目的,只是每当调用此方法时,浏览器都会自动进入默认大小并再次最大化。

每次调用屏幕截图功能时,这种情况都会继续。如果我不使用 selenium webdriver 截取屏幕截图并使用其他 java 函数,我能够解决这个问题。

我想知道是否有人有类似的问题/为什么我会遇到这个问题。有什么解决方法吗?

4

4 回答 4

2
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(scrFile, new File("D:\\screenshot.jpg"));

这段代码肯定会有所帮助

于 2012-10-30T13:02:21.987 回答
1

它会尝试适应页面大小并尽可能小或尽可能大地截取整个页面以适应整个页面。除了烦人之外,它不应该是任何其他问题的原因,因此被认为是比仅截取实际视口的屏幕截图更好的解决方案,因为实际视口可能会丢失您尝试检查的页面的某些重要部分。

如果您对此不满意,请使用Robot它的createScreenCapture()方法。


或者,但它只适用于 Firefox,您可以尝试覆盖FirefoxDriver's屏幕截图的方法。未经测试,不知道是否允许您这样做。

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("FirefoxDriver.prototype.screenshot = function(a){};");

并且(如果这还不够的话)甚至可能

js.executeScript("FirefoxDriver.prototype.saveScreenshot = function(a,b){};");

从这里推断。实际的屏幕截图代码在这里。您可以FirefoxDriver.prototype.screenshot用您自己的函数替换该函数,该函数不会为heightand width...

于 2012-06-08T20:42:02.533 回答
0

截图代码使用了 TakesScreenshot 接口的 getScreenshotAs 方法。以下代码将对 webDriver 实例打开的网页进行截图。

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg"));

现在为了在测试失败的情况下截屏,我们将使用 TestNG 的 AfterMethod 注释。在 AfterMethod 注释中,我们将使用 ITestResult 接口的 getStatus() 方法返回测试结果,如果失败,我们可以使用上述命令进行截图。用于在测试失败时截取屏幕截图的代码片段 -

@AfterMethod
public void takeScreenShotOnFailure(ITestResult testResult) throws IOException {
    if (testResult.getStatus() == ITestResult.FAILURE) {
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg"));
   }        
}

有关完整的示例脚本,请参阅http://artoftesting.com/automationTesting/screenShotInSelenium.html

于 2014-06-21T07:27:44.890 回答
0

我为此创建了一个方法,该方法非常易于使用。它截取整个网页的屏幕截图。它根据屏幕截图的数量对屏幕截图进行计数和命名,该方法还将屏幕截图作为 .png 文件存储到 src 中。

public static void screenshot(WebDriver driver) 
{

    System.out.println("Taking the screenshot.");   
    console_logs("Taking the screenshot.");
    scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    try {
        FileUtils.copyFile(scrFile, new File("src//tempOutput//webPage_screenshot_"+count+".png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    count++;
    //return scrFile;
}

使用方法:

screenshot(driver);
于 2016-05-10T17:23:59.380 回答