基本的例子

假设我们正在使用 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 的方法很少 - 检查语法部分。