简体   繁体   English

如何在Selenium Webdriver中使用Robot Framework截屏

[英]How to Take screenshot using Robot Framework in selenium webdriver

I'm working on an automation project in java using selenium. 我正在使用selenium在Java中进行自动化项目。 When there is a failure, need to take a screenshot of web view. 发生故障时,需要截取网络视图的屏幕截图。 Used TakesScreenshot and it's working fine both in chrome-driver and in phantomjs-driver . 使用了TakesScreenshot ,它在chrome驱动程序phantomjs-driver中都可以正常工作。

But this fails when an alert box is present. 但是,当出现警报框时,此操作将失败。 After some research, I understood that Selenium can't take a screenshot if alert is present. 经过一些研究,我了解到如果存在警报,Selenium无法截屏。 Alert must be handled first. 警报必须首先处理。 And I can use java.awt.Robot , in such scenario, where the alert box is needed in my screenshot. 在这种情况下,我的屏幕快照中需要警报框,因此我可以使用java.awt.Robot

But Robot takes screenshot of my screen and won't get the web view, if using phantomjs-driver or if chrome is running minimized. 但是,如果使用phantomjs-driver或chrome正在最小化运行, Robot会截取我的屏幕截图,但无法获得网络视图。 But I need the screenshot with alert box (which represents the failure condition). 但是我需要带有警告框的屏幕截图(代表故障情况)。

Is there any other solution for this issue? 这个问题还有其他解决方案吗?

If you really want to capture the screen with alert then there is a way. 如果您真的想捕获带有警报的屏幕,那么有一种方法。 Put your code portion for taking screenshot inside a try-catch block. 将用于截屏的代码部分放在try-catch块中。 If any alert found, it will throw an exception and in the catch block handle it. 如果发现任何警报,它将引发异常并在catch块中对其进行处理。

Code snippet: 程式码片段:

Alert alert = null;

    try {
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File("screenshot.png"));
    } catch (Exception e) {
        alert = driver.switchTo().alert();
        if(e.getMessage().contains("unexpected alert open:")){
            //before taking screenshot, you may wait for some moment to be properly visible
            try {
                 BufferedImage screencapture = new Robot().createScreenCapture((new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())));

                     File file = new File("screenshot.jpg");
                     ImageIO.write(screencapture, "png", file);
            } catch (AWTException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    alert.accept(); //or you can use dismiss();

Note: For taking screenshot using robot your window must be visible. 注意:要使用机械手拍摄屏幕截图,您的窗口必须可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM