How to get value of WebElement init in PageFactory?



  • For example:

    @FindBy(xpath = "//div[@id='panel']//span[@class='name']")
    private WebElement panel;
    

    I've got a panel element. Is it possible to get value of XPath that I init above?

    I need a solution how can I return:

    //div[@id='panel']//span[@class='name']

    string in a test.



  • Unfortunately you can not. You can see the WebElement interface here.

    The closest you can do is to call getAttribute and you could extract an ID or a specific class name.

    However, you can create a wrapper over WebElement that stores the locator:

    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 WebElement getLocator() {
            return by;
        }
    
    }
    

    Selenium's @FindBy annotation really takes control of the element initiation; if you want to have some control over it, you would have to drop @FindBy and implement its mechanisms yourself.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2