Get the By locator of an already found WebElement

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()


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
}