Get the By locator of an already found WebElement Get the By locator of an already found WebElement selenium selenium

Get the By locator of an already found WebElement


No, there's not. I have implemented a possible solution as a proxy:

public class RefreshableWebElement implements WebElement {    public RefreshableWebElement(Driver driver, By by) {        this.driver = driver;        this.by = by;    }    // ...    public WebElement getElement() {        return driver.findElement(by);    }    public void click() {        getElement().click();    }    // other methods here}


tldr; Not by default, no. You cannot extract a By from a previously found WebElement. It is possible, however, through a custom solution.

It's possible to implement a custom solution, but Selenium does not offer this out-of-the-box.

Consider the following, on "why"..

By by = By.id("someId");WebElement e = driver.findElement(by);

you already have the By object, so you wouldn't need to call something like e.getBy()


There is no elegant way provided by Selenium. And this is horrible

1) PageObject and PageFactory implies that we have WebElements in Page classes, but we don't have locators of those elements.

2) If I find element as descendant of current element using webElement.findElement(By), then I don't have the locator of this descendant even if I stored parent's locator in the variable.

3) If I use findElements function that returns List of elemetns, then I don't have locator for each specific element.

4) Having locator for element is useful at least because ExpectedConditions with locator as parameter are much better implemented than ExpectedConditions with WebElement as parameter.

For me Selenium is ill-conceived and poorly implemented library