Converting a WebElement type to a By type
Asked Answered
M

4

8

Is there any way to convert a WebElement type object to a By in selenium? Type casting did not work.

I have a function which only takes in By's, so I need to convert a WebElement to a By.

Maffick answered 7/4, 2014 at 20:59 Comment(5)
I guess the function you already have uses the By to get a WebElement? Probably overloading the method will be the way to go.Cytology
I don't think there's a way to do that. I think I'd need to see what you're trying to accomplish to suggest a good solution. My offhand suggestion is to create an object that has WebElement and By properties, and pass in element.By to your method.Ingravescent
You could get the absolute xpath of the webelement using javascript and then create a By object from it.Buffet
This isn't going to work. A WebElement isn't a By object in any sense. That's the point. So perhaps you should explain what you are trying to accomplish.Sarmatia
I also have this problem My issue is that I have found an item, and then need to find a child of that item. parent = Find.By.Xpath(whatever) child = item.Find.By.Xpath(".//" + whatever2) But I need to pass the child's by to a method. I can use the by by itself, but then how do I limit the xpath to children of parent?Inmate
S
4

If you are using a method which takes an argument of a WebElement, it is likely that you are considering the problem in a way that would be less effective than if you passed it a by selector instead. However, this method should fulfill your ask.

// return ByType of WebElement
public By toByVal(WebElement we) {
    // By format = "[foundFrom] -> locator: term"
    // see RemoteWebElement toString() implementation
    String[] data = we.toString().split(" -> ")[1].replace("]", "").split(": ");
    String locator = data[0];
    String term = data[1];

    switch (locator) {
    case "xpath":
        return By.xpath(term);
    case "css selector":
        return By.cssSelector(term);
    case "id":
        return By.id(term);
    case "tag name":
        return By.tagName(term);
    case "name":
        return By.name(term);
    case "link text":
        return By.linkText(term);
    case "class name":
        return By.className(term);
    }
    return (By) we;
}
Swami answered 15/3, 2016 at 14:7 Comment(0)
A
1

I use this method and it works fine for me. To run this code block it requires Apache Commons IO library.

 /**
     * Converting WebElement to By locator
     *
     * @param webElement
     * @return By
     */
    public static By getByLocator(WebElement webElement) {
        String element = webElement.toString().split(
                "(?=\\sid:\\s|\\sname:\\s|\\sselector:\\s|\\slink text:|\\sxpath:\\s|" +
                        "By.id:\\s|By.name:\\s|By.tagName:\\s|By.className:\\s|By.cssSelector:\\s|" +
                        "By.linkText:\\s|By.partialLinkText:\\s|By.xpath:\\s)")[1];

        String[] locator = StringUtils.removeEnd(element, "]").split(":\\s");
        String method = locator[0].trim();
        if (method.equals("xpath"))
            return By.xpath(locator[1]);

        String selector = StringUtils.removeEnd(locator[1], "'");
        switch (method) {
            case "id":
            case "By.id":
                return By.id(selector);
            case "name":
            case "By.name":
                return By.name(selector);
            case "By.tagName":
                return By.tagName(selector);
            case "By.className":
                return By.className(selector);
            case "selector":
            case "By.cssSelector":
                return By.cssSelector(selector);
            case "By.linkText":
                return By.linkText(selector);
            case "link text":
            case "By.partialLinkText":
                return By.partialLinkText(selector);
            case "By.xpath":
                return By.name(selector);
            default:
                System.out.println("Error! [" + method + "]");
                return null;
        }
    }
Adachi answered 8/9, 2021 at 6:29 Comment(0)
M
0

This could help.

private static WebElement returnElement(String stringElement) {
    if (stringElement == null) {
        return null;
    } else if (stringElement.contains("->")) {
        String[] splitElement = stringElement.split(" ");
        String locatorType = splitElement[6].replace(":", "");
        String locatorPath = null;
        if(locatorType.equalsIgnoreCase("xpath")) {
            locatorPath = stringElement.substring(stringElement.indexOf("//"), stringElement.length() -1);
        } else {
            locatorPath = splitElement[7].substring(0, splitElement[7].length() - 1);
        } 
        return returnElement(locatorType, locatorPath);
    } else {
        String[] splitElement = stringElement.split(" ");
        String locatorType = splitElement[4].substring(splitElement[4].lastIndexOf(".") + 1,
                splitElement[4].lastIndexOf(":"));
        int index = splitElement[5].length();
        String locatorPath = splitElement[5].substring(0, index - 1);
        return returnElement(locatorType, locatorPath);
    }
}

// Refreshing DOM Elements
private static WebElement returnElement(String locatorType, String locatorPath) {
    switch (locatorType.toLowerCase()) {
    case "id":
        return driver.findElement(By.id(locatorPath));

    case "xpath":
        return driver.findElement(By.xpath(locatorPath));

    case "name":
        return driver.findElement(By.name(locatorPath));

    case "classname":
        return driver.findElement(By.className(locatorPath));

    case "cssselector":
        return driver.findElement(By.cssSelector(locatorPath));

    case "linktext":
        return driver.findElement(By.linkText(locatorPath));

    case "tagname":
        return driver.findElement(By.tagName(locatorPath));

    default:
        throw new RuntimeException("Unknown locator " + locatorType + " : " + locatorPath);
    }
}
Macaco answered 6/7, 2016 at 13:23 Comment(0)
E
0

You can also use the getBy() for converting into By element

let's say you got the following code

@FindBy (id = "some-id-goes-here")
private static ExtendedWebElement MyElementById;


public static ExtendedWebElement getMyElementById(){
    return MyElementById;
}

now you can convert it into By element like this

getMyElementById().getBy()

and use it inside ExpectedConditions.visibilityOfElementLocated(getMyElementById().getBy())

Edibles answered 6/3, 2023 at 13:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.