如何在katalon studio中将WebElement转换为TestObject?

How to convert WebElement to TestObject in katalon studio?

我有 WebElement,我必须使用 groovy 脚本将其转换为 katalon 中的 Testobject。

例如

List<WebElement> WEs = WebUI.executeJavaScript("return document.querySelector('#email').parentElement", [])

现在我想将 WEs[0] 转换为 Katalon 接受的 TestObject。

如果您对此有任何想法,请告诉我。

没有将 WebElements 转换为 TestObjects 的直接方法。根据 this forum question,你可以创建一个函数来获取 web 元素的 xpath

protected String getXPathFromElement(RemoteWebElement element) {
    String elementDescription = element.toString();
    return elementDescription.substring(elementDescription.lastIndexOf("-> xpath: ") + 10, elementDescription.lastIndexOf("]"));
}

然后使用给定的 xpath 创建一个新的测试对象:

protected TestObject fromElement(RemoteWebElement element) {
    TestObject testObject = new TestObject();
    testObject.addProperty("xpath", ConditionType.EQUALS, getXPathFromElement(element));
    return testObject;
}


注意:

对于其他方式(测试对象 -> WebElement),使用

WebUiCommonHelper.findWebElement(test-object, timeout)

为了从任何 WebElement 创建测试对象,我开发了如下函数

public static String WebElementXPath(WebElement element) {
    if (element.tagName.toUpperCase() == 'HTML')    return '/html';
    if (element.tagName.toUpperCase() == 'BODY')      return '/html/body';


    // calculate position among siblings
    int position = 0;
    // Gets all siblings of that element.
    List<WebElement> siblings = WebUI.executeJavaScript("return arguments[0].parentNode.childNodes", [element])
    WebElement innerSibs
    //List<WebElement> siblings = element.parentNode.childNodes;

    WebElement sibling
    def type,response
    for(int i=0;i<siblings.size();i++){
        type = WebUI.executeJavaScript("return arguments[0].nodeType", [siblings[i]])
        if (type == null){
            continue;
        }
        if(type!=1){
            continue;
        }
        sibling = siblings[i];
        // Check Siblink with our element if match then recursively call for its parent element.
        if (sibling == element) {
            innerSibs = WebUI.executeJavaScript("return arguments[0].parentElement", Arrays.asList(sibling))
            if(innerSibs==null){
                return ""
            }
            response = functions.WebElementXPath(innerSibs)
            return response+'/'+element.tagName+'['+(position+1)+']';

        }

        // if it is a siblink & element-node then only increments position.
        type = WebUI.executeJavaScript("return arguments[0].nodeType", [sibling])
        if (type == 1 && sibling.tagName == element.tagName)            position++;

    }
}

然后我按照 Mate Mrše 的建议创建了获取测试对象的函数

public static TestObject getTestObjectFromWebElement(WebElement element) {
    TestObject object = new TestObject()
    object.addProperty("xpath", ConditionType.CONTAINS, functions.WebElementXPath(element))
    return object
}

注意:"Framework" 文件夹是我们在关键字文件夹中创建的,然后我们创建了 "functions" 关键字

我希望这可能对其他开发人员有所帮助。

WebUI.convertWebElementToTestObject()