You need to enable JavaScript to run this app. 如何实现PageFactory结合Fluent Wait等待比价网站价格完全加载?
优惠活动
大模型
产品
解决方案
定价
更多

如何实现PageFactory结合Fluent Wait等待比价网站价格完全加载?

Hey there! I feel your pain—implicit waits can be flaky, hard sleeps are never a good practice (they slow down tests and are unreliable), and figuring out how to pair PageFactory with the modern Fluent Wait implementation can be confusing since the old FluentWait class is deprecated. Let's break down exactly how to make this work smoothly.

Modern Fluent Wait Basics First

First, let's cover the updated way to use Fluent-style waits in modern Selenium. The old FluentWait constructor is deprecated, but we can achieve the same flexible behavior using WebDriverWait with chained methods:

// Setup a modern Fluent-style wait
Wait<WebDriver> fluentWait = new WebDriverWait(driver, Duration.ofSeconds(10))
        .pollingEvery(Duration.ofMillis(500)) // Check for the element every 500ms
        .ignoring(NoSuchElementException.class) // Ignore common lookup exceptions while waiting
        .ignoring(StaleElementReferenceException.class);

This gives you full control over timeout duration, polling frequency, and which exceptions to ignore—core features of Fluent Wait.

Option 1: Global Fluent Wait with Custom PageFactory Locator

If you want consistent waiting behavior across all elements in your page objects, this approach lets PageFactory automatically apply Fluent Wait whenever it looks up elements.

Step 1: Create a Custom Element Locator Factory

This factory will tell PageFactory to use our Fluent Wait when locating elements:

public class FluentWaitElementLocatorFactory implements ElementLocatorFactory {
    private final WebDriver driver;
    private final Wait<WebDriver> wait;

    public FluentWaitElementLocatorFactory(WebDriver driver, Wait<WebDriver> wait) {
        this.driver = driver;
        this.wait = wait;
    }

    @Override
    public ElementLocator createLocator(Field field) {
        return new FluentWaitElementLocator(driver, field, wait);
    }
}

Step 2: Create a Custom Element Locator

This locator wraps the default element lookup with our Fluent Wait:

public class FluentWaitElementLocator extends DefaultElementLocator {
    private final Wait<WebDriver> wait;

    public FluentWaitElementLocator(WebDriver driver, Field field, Wait<WebDriver> wait) {
        super(driver, field);
        this.wait = wait;
    }

    @Override
    protected WebElement findElement() {
        // Use Fluent Wait to ensure the element exists before returning it
        return wait.until(driver -> super.findElement());
    }

    @Override
    protected List<WebElement> findElements() {
        return wait.until(driver -> super.findElements());
    }
}

Step 3: Initialize Your Page Object with the Custom Factory

Instead of using the default PageFactory initialization, pass in our custom factory:

// Setup your Fluent Wait first
Wait<WebDriver> fluentWait = new WebDriverWait(driver, Duration.ofSeconds(10))
        .pollingEvery(Duration.ofMillis(500))
        .ignoring(NoSuchElementException.class);

// Initialize the page object with the custom Fluent Wait factory
LoginPage loginPage = PageFactory.initElements(new FluentWaitElementLocatorFactory(driver, fluentWait), LoginPage.class);

Now any time you access an element from loginPage, it will automatically use your Fluent Wait to ensure the element exists before returning it.

Option 2: Per-Action Fluent Wait (More Flexible)

If you need different waiting strategies for different elements or actions (e.g., wait for clickability for a button, wait for visibility for a text field), this approach gives you granular control. Define the Fluent Wait in your page class and use it explicitly when interacting with elements.

Here's an example page class:

public class LoginPage {
    private final WebDriver driver;
    private final Wait<WebDriver> fluentWait;

    @FindBy(id = "username")
    private WebElement usernameInput;

    @FindBy(id = "password")
    private WebElement passwordInput;

    @FindBy(id = "login-btn")
    private WebElement loginButton;

    public LoginPage(WebDriver driver) {
        this.driver = driver;
        // Configure Fluent Wait for this page
        this.fluentWait = new WebDriverWait(driver, Duration.ofSeconds(10))
                .pollingEvery(Duration.ofMillis(500))
                .ignoring(NoSuchElementException.class)
                .ignoring(ElementNotInteractableException.class);
        
        // Initialize elements with default PageFactory
        PageFactory.initElements(driver, this);
    }

    public void enterUsername(String username) {
        // Wait for the input to be clickable before sending keys
        WebElement readyInput = fluentWait.until(ExpectedConditions.elementToBeClickable(usernameInput));
        readyInput.sendKeys(username);
    }

    public void clickLoginButton() {
        // Wait specifically for the button to be clickable
        WebElement readyButton = fluentWait.until(ExpectedConditions.elementToBeClickable(loginButton));
        readyButton.click();
    }
}

This lets you tailor waits to specific actions, which is perfect for dynamic pages with AJAX loads.

Quick Note on Why Implicit Wait Failed

Implicit waits are global and only wait for an element to exist in the DOM—not for it to be visible, interactable, or ready for action. If your page uses asynchronous loading (like fetching content after page load), implicit wait won't wait for those elements to be usable. Also, mixing implicit and explicit waits can lead to unexpected wait times, which might have made it seem like the implicit wait wasn't working.

内容的提问来源于stack exchange,提问作者john2020

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 16:28:10