</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

What are @FindBys and @FindAll annotations in Selenium PageFactory?

Answer

@FindBys and @FindAll in PageFactory

These annotations extend @FindBy to support compound locators — finding elements that satisfy multiple criteria.

@FindBy (Single Locator)

Java
@FindBy(id = "username")
private WebElement usernameField;

@FindBys — AND Logic (All Must Match)

All inner @FindBy conditions must be satisfied (chained lookup):

Java
// Find <input> that is a descendant of <div class="form-group">
// AND has name="email"
@FindBys({
    @FindBy(className = "form-group"),
    @FindBy(name = "email")
})
private WebElement emailInsideFormGroup;

Behavior: First finds div.form-group, then looks for [name="email"] inside it. Like chained CSS/XPath.

@FindAll — OR Logic (Any Can Match)

Elements matching any of the conditions are returned together:

Java
// Finds ALL elements that are either h1 OR h2 OR h3
@FindAll({
    @FindBy(tagName = "h1"),
    @FindBy(tagName = "h2"),
    @FindBy(tagName = "h3")
})
private List<WebElement> allHeadings;

Behavior: Union of results from all locators. Returns a list with duplicates possible.

Practical Examples

Java
public class SearchPage {
    WebDriver driver;

    // Single match
    @FindBy(css = "input[type='search']")
    private WebElement searchInput;

    // AND — find active nav item inside nav bar
    @FindBys({
        @FindBy(className = "navbar"),
        @FindBy(className = "active")
    })
    private WebElement activeNavItem;

    // OR — find all call-to-action buttons (different styles)
    @FindAll({
        @FindBy(className = "btn-primary"),
        @FindBy(className = "btn-cta"),
        @FindBy(css = "a.action-link")
    })
    private List<WebElement> ctaButtons;

    public SearchPage(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    public void clickFirstCTA() {
        ctaButtons.get(0).click();
    }
}

Comparison Table

AnnotationLogicUse Case
@FindBySingle locatorStandard element location
@FindBysAND (all conditions)Element nested inside another
@FindAllOR (any condition)Collect elements of multiple types

Important Notes

  • @FindBys chaining requires the elements to be nested — first locator finds a container, subsequent ones search within it
  • @FindAll can return duplicates if an element matches multiple conditions
  • Both work with List<WebElement> for multiple elements
  • PageFactory.initElements() is still required to initialize all @FindBy* annotated fields

Follow AutomateQA

Related Topics