Answer
@FindBys and @FindAll in PageFactory
These annotations extend @FindBy to support compound locators — finding elements that satisfy multiple criteria.
@FindBy (Single Locator)
@FindBy(id = "username")
private WebElement usernameField;
@FindBys — AND Logic (All Must Match)
All inner @FindBy conditions must be satisfied (chained lookup):
// 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:
// 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
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
| Annotation | Logic | Use Case |
|---|---|---|
@FindBy | Single locator | Standard element location |
@FindBys | AND (all conditions) | Element nested inside another |
@FindAll | OR (any condition) | Collect elements of multiple types |
Important Notes
- ✓
@FindByschaining requires the elements to be nested — first locator finds a container, subsequent ones search within it - ✓
@FindAllcan 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
