@FindBy annotations help you find web elements on a page easily without writing long code. They make your test code cleaner and easier to read.
@FindBy annotations in Selenium Java
@FindBy(how = How.ID, using = "elementId")
private WebElement elementName;You can use different locator types like id, name, xpath, css, etc.
The annotation is placed above the WebElement variable declaration.
@FindBy(id = "submitBtn")
private WebElement submitButton;@FindBy(name = "username")
private WebElement usernameField;@FindBy(xpath = "//div[@class='alert']")
private WebElement alertMessage;@FindBy(css = ".nav-menu > li:nth-child(2)")
private WebElement secondMenuItem;This example shows a simple login page class using @FindBy annotations to locate username, password, and login button elements. The test class opens the browser, navigates to the login page, and performs a login.
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class LoginPage { @FindBy(id = "username") private WebElement usernameInput; @FindBy(id = "password") private WebElement passwordInput; @FindBy(id = "loginBtn") private WebElement loginButton; public LoginPage(WebDriver driver) { PageFactory.initElements(driver, this); } public void login(String user, String pass) { usernameInput.sendKeys(user); passwordInput.sendKeys(pass); loginButton.click(); } } // Test class example import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class LoginTest { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("https://example.com/login"); LoginPage loginPage = new LoginPage(driver); loginPage.login("testuser", "testpass"); System.out.println("Login attempted"); driver.quit(); } }
Always initialize elements with PageFactory.initElements() in the constructor.
Use meaningful variable names for WebElements to keep code readable.
Prefer specific locators like id or name over complex XPath for better speed and reliability.
@FindBy annotations simplify locating web elements in Selenium tests.
They help keep test code clean and organized, especially with Page Object Model.
Remember to initialize elements with PageFactory before using them.