Search code examples
seleniumselenium-webdriverxpathwebdriver

What's the purpose of By keyword in Selenium Java


Sample Code:

public class RediffLoginPage

{
    Webdriver driver;
    public RediffLoginPage(Webdriver driver){
        this.driver=driver;
    }

    By username=By.xpath(".//*(@id='login1']");
    By Password=By.name("passwd");
}

public Webelement Emailid()
{
    return driver.findElement(username);
}

public Webelement Password(){return driver.findElement(Password);}

In this line,

By username=By.xpath(".//*(@id='login1']");

what's the purpose of first By keyword here?

It's object repository code for a testcase.


Solution

  • Class By

    Class By extends java.lang.Object and is defined as:

    public abstract class By
    extends java.lang.Object
    
    Mechanism used to locate elements within a document. In order to create your own locating mechanisms, it is possible to subclass this class and override the protected methods as required, though it is expected that all subclasses rely on the basic finding mechanisms provided through static methods of this class:
    
     public WebElement findElement(WebDriver driver) {
         WebElement element = driver.findElement(By.id(getSelector()));
         if (element == null)
           element = driver.findElement(By.name(getSelector());
         return element;
     }
     
    

    By have the following direct known Subclasses: