使用Katalon和Chrome无头模式的屏幕截图

时间:2018-07-04 08:02:56

标签: groovy screenshot google-chrome-headless katalon-studio

我正在使用以下代码在我的Katalon Studio脚本中截取警告和错误消息的屏幕截图:

import ru.yandex.qatools.ashot.AShot
import ru.yandex.qatools.ashot.Screenshot
import ru.yandex.qatools.ashot.coordinates.*
import ru.yandex.qatools.ashot.cropper.*

public class ScreenshotHelper {


  public void takeWebElementScreenshot(TestObject object) {
    WebElement element = WebUiCommonHelper.findWebElement(object, 20)
    WebDriver driver = DriverFactory.getWebDriver();
    String fileName = new SimpleDateFormat("yyyyMMddHHmmSSS").format(new Date())
    Screenshot screenshot = new AShot().takeScreenshot(driver, element)
    ImageIO.write(screenshot.getImage(),'PNG', new File(System.getProperty("user.dir")+"/ErrorScreenshots/ElementScreenshot"+"_"+fileName+".png"))
  }
}

此方法从同一类的另一个方法调用:

public void catchNotyMessage(){

TestObject noty_warning = WebUI.modifyObjectProperty(findTestObject("DUMMY"), 'css', 'equals', 'div.noty_type_warning', true)
TestObject noty_error = WebUI.modifyObjectProperty(findTestObject("DUMMY"), 'css', 'equals', 'div.noty_type_error', true)

    if (WebUI.verifyElementPresent(noty_error, 1, FailureHandling.OPTIONAL)){
        this.takeWebElementScreenshot(noty_error)
    }
    else if (WebUI.verifyElementPresent(noty_warning, 1, FailureHandling.OPTIONAL)){
        this.takeWebElementScreenshot(noty_warning)
    }
}

它工作正常,在正常模式下使用Katalon时截取了屏幕截图。

但是,当我以无头模式运行脚本时,会收到以下警告:

WARNING com.kms.katalon.core.webui.exception.WebElementNotFoundException: Web element with id: 'Object Repository/DUMMY' located by 'By.cssSelector: div.noty_type_error' not found

即使该元素应该存在。测试失败,并显示java.lang.NullPointerException

是因为无头执行吗?我该如何解决?

2 个答案:

答案 0 :(得分:1)

您必须将参数设置为无头Chrome:

enter image description here

答案 1 :(得分:1)

浏览了https://docs.oracle.com/javase/tutorial/2d/images/saveimage.htmljava.io.FileNotFoundException: the system cannot find the file specifiedChrome Headless Doesn't workJava "user.dir" property - what exactly does it mean?之后,我终于明白了。

问题在于,在无头模式下通过命令行执行测试时,System.getProperty("user.dir")会发生变化。因此,此代码有效:

    public void takeWebElementScreenshot(TestObject object) {
    WebElement element = WebUiCommonHelper.findWebElement(object, 20)
    WebDriver driver = DriverFactory.getWebDriver();
    String fileName = new SimpleDateFormat("yyyyMMddHHmmSSS").format(new Date())
    Screenshot screenshot = new AShot().takeScreenshot(driver, element)
    try {
        if (DriverFactory.getExecutedBrowser().getName()=='HEADLESS_DRIVER'){
            ImageIO.write(screenshot.getImage(),'PNG', new File("C:/Users/path_to_working_directory/ErrorScreenshots/HeadlessElementScreenshot"+"_"+fileName+".png"))
        } else {
            ImageIO.write(screenshot.getImage(),'PNG', new File(System.getProperty("user.dir")+"/ErrorScreenshots/ElementScreenshot"+"_"+fileName+".png"))
        }

    } catch (Exception e) {
        e.printStackTrace()
    }
}