基本的例子

假設我們正在使用 Page 物件模型 。頁面物件類:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginPage {
    
    @FindBy(id="loginInput") //method used to find WebElement, in that case Id
    WebElement loginTextbox;
    
    @FindBy(id="passwordInput")
    WebElement passwordTextBox;
    
    //xpath example:
    @FindBy(xpath="//form[@id='loginForm']/button(contains(., 'Login')") 
    WebElement loginButton;
    
    public void login(String username, String password){
        // login method prepared according to Page Object Pattern
        loginTextbox.sendKeys(username);
        passwordTextBox.sendKeys(password);
        loginButton.click();
        // because WebElements were declared with @FindBy, we can use them without
        // driver.find() method
    }
}

和測試類:

class Tests{
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        LoginPage loginPage = new LoginPage();

        //PageFactory is used to find elements with @FindBy specified
        PageFactory.initElements(driver, loginPage);
        loginPage.login("user", "pass");
    }
}

使用 @FindBy 查詢 WebElements 的方法很少 - 檢查語法部分。