Get the By locator of an already found WebElement

前端 未结 6 1245
眼角桃花
眼角桃花 2020-12-15 17:57

Is there an elegant way to get the By locator of a Selenium WebElement, that I already found/identified?

To be clear about the question: I want the

6条回答
  •  春和景丽
    2020-12-15 18:34

    Currently there is no specific method from selenium's end to do so. What you can do is write your custom method. You will get the clue of what selector type and path is used by just printing the webElement you have.

    It looks something like this

    [[ChromeDriver: chrome on XP (d85e7e220b2ec51b7faf42210816285e)] -> xpath: //input[@title='Search']]

    Now, what you need to do is to extract the locator and its value. You can try something like this

    `private By getByFromElement(WebElement element) {

        By by = null;
        //[[ChromeDriver: chrome on XP (d85e7e220b2ec51b7faf42210816285e)] -> xpath: //input[@title='Search']]
        String[] pathVariables = (element.toString().split("->")[1].replaceFirst("(?s)(.*)\\]", "$1" + "")).split(":");
    
        String selector = pathVariables[0].trim();
        String value = pathVariables[1].trim();
    
        switch (selector) {
            case "id":
                by = By.id(value);
                break;
            case "className":
                by = By.className(value);
                break;
            case "tagName":
                by = By.tagName(value);
                break;
            case "xpath":
                by = By.xpath(value);
                break;
            case "cssSelector":
                by = By.cssSelector(value);
                break;
            case "linkText":
                by = By.linkText(value);
                break;
            case "name":
                by = By.name(value);
                break;
            case "partialLinkText":
                by = By.partialLinkText(value);
                break;
            default:
                throw new IllegalStateException("locator : " + selector + " not found!!!");
        }
        return by;
    }
    

    `

提交回复
热议问题