The feature that makes Page Factory most interesting is that the element finding is done in the background, without the need to use any code in the page classes for this purpose.
For example, in this class, there is no code for finding any of the elements:
public class HomePage {
private WebDriver driver;
private static final String HOME_PAGE_URL = "https://www.vpl.ca/";
@FindBy(id = "edit-search")
private WebElement searchBox;
@FindBy(id = "edit-submit")
private WebElement searchButton;
public HomePage(WebDriver driver) {
PageFactory.initElements(driver, this);
this.driver = driver;
}
public void open() {
driver.get(HOME_PAGE_URL);
}
public boolean isDisplayed() {
return getUrl().equalsIgnoreCase(HOME_PAGE_URL);
}
public String getUrl() {
return driver.getCurrentUrl();
}
public ResultsPage searchBy(String keyword) {
typeKeyword(keyword);
clickSearchButton();
return new ResultsPage(driver);
}
public void typeKeyword(String keyword) {
searchBox.sendKeys(keyword);
}
public void clickSearchButton() {
searchButton.click();
}
}
Both searchBox and searchButton are simply used, being found by the page factory in the background right before they are needed for the first time.
Page Factory works well if the page loads fast but if the page is slow, it will start throwing ElementNotFound exceptions.
Why does it do this for slow pages?
If the page is slowly loading, the element may not be yet in the page when page factory tries finding it. Since page factory uses the findElement() method of the driver to locate the element, if the element is not there, there is no waiting for the element so an exception is generated.
Keep reading with a 7-day free trial
Subscribe to Selenium For Beginners to keep reading this post and get 7 days of free access to the full post archives.