Get the By locator of an already found WebElement

how to find more than one web element in the list
what is webdriver and webelement
is webelement present
webelement interface
how to store xpath in webelement
how to retrieve xpath from webelement
selenium webelement xpath
how to convert xpath to webelement

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 "By locator" as used to find the element. I am in this case not interested in a specific attribute or a specific locator like the css-locator.

I know that I could parse the result of a WebElement's toString() method:

WebElement element = driver.findElement(By.id("myPreciousElement"));
System.out.println(element.toString());

Output would be for example:

[[FirefoxDriver: firefox on WINDOWS (....)] -> id: myPreciousElement]

if you found your element by xpath:

WebElement element = driver.findElement(By.xpath("//div[@someId = 'someValue']"));
System.out.println(element.toString());

Then your output will be:

[[FirefoxDriver: firefox on WINDOWS (....)] -> xpath: //div[@someId = 'someValue']]

So I currently wrote my own method that parses this output and gives me the "recreated" By locator.

BUT is there a more elegant way already implemented in Selenium to get the By locator used to find the element?
I couldn't find one so far.

If you are sure, there is none out of the box, can you think of any reason why the API creators might not provide this functionality?

*Despite the fact that this has nothing to do with the question, if someone wonders why you would ever need this functionality, just 2 examples:

  • if you use PageFactory you most likely will not have the locators as as member variables in your Page class, but you might need them later on when working with the page's elements.
  • you're working with APIs of people who just use the Page Object Pattern without PageFactory and thus expect you to hand over locators instead of the element itself.*

Answer is No. You cannot extract a By from a previously found WebElement by default.

That being said - 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()

java - Get the By locator of an already found WebElement, Answer is No. You cannot extract a By from a previously found WebElement by default. That being said - it's possible to implement a custom solution, but  FindElement command syntax: Find Element command takes in the By object as the parameter and returns an object of type WebElement. By object in turn can be used with various locator strategies such as ID, Name, Class Name, XPATH etc. Below is the syntax of FindElement command in Selenium web driver.

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
}

[SOLVED] Get the By locator of an already found WebElement , Answer is No. You cannot extract a By from a previously found WebElement by default. That being said - it's possible to implement a custom  WebElement textDemo = driver.findElement(By.xpath(“//*”)); Text() Method of Selenium Text() method is a built-in method of selenium web driver that can be used to locate an element based on the text of the web element.

For me worked with commons-lang3

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
</dependency>

For remote web element use method like:

protected String getLocator(WebElement element) {
        try {
            Object proxyOrigin = FieldUtils.readField(element, "h", true);
            Object locator = FieldUtils.readField(proxyOrigin, "locator", true);
            Object findBy = FieldUtils.readField(locator, "by", true);
            if (findBy != null) {
                return findBy.toString();
            }
        } catch (IllegalAccessException ignored) {
        }
        return "[unknown]";
    }

java: Get the By locator of an already found WebElement, 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  You can always output the locator used using webElement.locator().toString(). Check the output for the below code snipper. Check the output for the below code snipper. Protractor spec:

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

Get locator value using java webdriver selenium, 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  in this case WebElement identified by path locator (in this case “xpath”) has been found. Unfortunately, a lot of time, the WebElement isn’t already loaded at the time previous code line execution (remember: usually Selenium is faster then your browser), so your test execution get exceptions (i.e. “No such element…”).

I had written this utility function which returns a string combination of locator strategy + locator value.

private String getLocatorFromWebElement(WebElement element) {

    return element.toString().split("->")[1].replaceFirst("(?s)(.*)\\]", "$1" + "");
}

Any easy way to get the By locator from a WebElement?, findElement(By.xpath("//span[@title='Error - Unresolved']"));. If you already have an instance of a WebElement and need to have its title attribute  Instead of passing in an XPath as a string, instead pass a By locator. Now you can use any locator type you want. Now you can use any locator type you want. I've rewritten and simplified your code and then written the similar function that takes in a WebElement parameter.

java - Get the By locator of an already found WebElement -, If the By locator was an accessible property of WebElement, that would be very handy! The only post I could find that sounded similar was WebElement activeElement() Switches to the element that currently has focus within the document currently "switched to", or the body element if this cannot be detected. This matches the semantics of calling "document.activeElement" in Javascript.

Retrieving xpath from stored webelement variable, is there elegant way locator of selenium webelement, found/identified? to clear question: want "by locator" used find element. in case not  Lets say you have already located one or more elements in your test and you want to identify them by their 'type' html attribute // Lets locate the first found input tag WebElement someElement = driver.findElement(By.cssSelector("input")); // And now lets store it's type String typeOfElement = someElement.getAttribute("type");

How to extract xpath of a Webelement · Issue #5520 · SeleniumHQ , i can think of one way of getting you the class name instead of the whole xpath, index to get locator name String locator = temp2[0]; //Access Second index to  WebElement Ele = driver.findElement(By.id("toolbar")); Unfortunately there are many cases where an element does not have a unique id (or the ids are dynamically generated and unpredictable like GWT). In these cases we need to choose an alternative locator strategy, however if possible we should ask development team of the web application to add

Comments
  • possible duplicate of How to get a CSS selector using Selenium WebDriver?
  • don't think this is a duplicate with your proposed question, because I'm specifically interested in the By locator. As you answered in that other question, this would make more sense then retrieving the "css" locator, which might not exist, but there is always a By locator to retrieve an element
  • Did you ever figure this out? I am using the PageFactory implementation and have basically no way to verify that an element is displayed or not.
  • that being said - it's not possible as it stands. you can implement a custom solution, but Selenium does not support this out-of-the-box
  • any idea why this might is not provided by the API? Do you think this is intentional for some reason?
  • well i'm actually a maintainer of the project, and it's not implemented because there's typically no reason to need to find the by of an element. easier just to say WebElement theElement = d.findElement(b) and you already have b saved somewhere. I could implement this, but it'd take a while. we're welcoming of pull requests :) github.com/seleniumhq/selenium
  • But for PageObject and PageFactory pattern, The By is defined in annotation, the element itself cannot know By
  • Hi, almost 2 years now since this question was asked. May I know if an implementation for this has been done? Thanks!
  • nice idea with the refreshable element, will use it in the future, can you think of any reason why Selenium creators might not have provided this functionality intentionally?
  • I think they omitted this because WebElements can be located by complex sequences. For example, WebElement header = driver.findElement(By.id("table-id")).findElement(By.tagName("table")).findElements(By.xpath(".//th")).get(0);. How would you save references to all of those By locators?
  • It is a path of locators.
  • Wouldn't work for elements found using @FindBy annotation