Custom Waits

Introduction

Selenium provides built-in synchronization mechanisms such as Implicit Wait, Explicit Wait, and Fluent Wait. However, there are situations where the available Expected Conditions are not sufficient for a specific automation requirement.

In such cases, Selenium allows you to create Custom Waits, where you define your own waiting condition based on your application’s behavior.

Custom Waits provide greater flexibility and are especially useful when automating complex, dynamic web applications.

In this tutorial, you’ll learn what Custom Waits are, why they are used, practical examples, real-world use cases, common mistakes, and best practices.


What are Custom Waits?

A Custom Wait is a user-defined waiting condition that repeatedly checks whether a specific condition has been met before continuing execution.

Instead of using Selenium’s predefined Expected Conditions, you write your own condition based on your application’s requirements.

Custom Waits are typically implemented using WebDriverWait together with a custom function or a lambda expression.


Why Use Custom Waits?

Custom Waits help you:

  • Handle application-specific scenarios.

  • Wait for custom JavaScript changes.

  • Wait for complex UI updates.

  • Improve synchronization for dynamic applications.

  • Reduce flaky automation tests.


Syntax

from selenium.webdriver.support.ui import WebDriverWait

wait = WebDriverWait(driver, 10)

wait.until(custom_condition)

Where:

  • WebDriverWait → Creates the Explicit Wait.

  • custom_condition → Your own function or lambda expression that returns True when the condition is satisfied.


Example

The following example waits until the text “Hello World!” appears inside the dynamically loaded content. Instead of using Selenium’s built-in Expected Conditions, a custom lambda function is used with WebDriverWait.until() to repeatedly check the element’s text until the required value appears.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait


# Topic: 24. Advanced Synchronization - Custom Waits
# Practice site: https://the-internet.herokuapp.com/dynamic_loading/1
# Run: pytest -s 24_examples/test_04_custom_waits.py
#
# A lambda or custom function can be passed to WebDriverWait.until() for
# conditions not covered by expected_conditions.


def test_custom_wait():
    driver = webdriver.Chrome()

    try:
        driver.get("https://the-internet.herokuapp.com/dynamic_loading/1")

        driver.find_element(
            By.CSS_SELECTOR,
            "#start button"
        ).click()

        WebDriverWait(driver, 10).until(
            lambda browser:
            "Hello World!" in browser.find_element(
                By.CSS_SELECTOR,
                "#finish"
            ).text
        )

        assert "Hello World!" in driver.find_element(
            By.CSS_SELECTOR,
            "#finish h4"
        ).text

    finally:
        driver.quit()

Output

Hello World!

The custom waiting condition
was satisfied successfully.

The dynamically loaded content
appeared before the timeout
period expired.

Understanding the Code

Import WebDriverWait

from selenium.webdriver.support.ui import (
    WebDriverWait
)

Imports Selenium’s Explicit Wait class that repeatedly checks whether a specified condition has been satisfied.


Open the Practice Website

driver.get(
    "https://the-internet.herokuapp.com/dynamic_loading/1"
)

Opens Selenium’s Dynamic Loading practice page.

The content displayed on this page is loaded dynamically after clicking the Start button, making it ideal for demonstrating Custom Waits.


Click the Start Button

driver.find_element(
    By.CSS_SELECTOR,
    "#start button"
).click()

Clicking the button begins the dynamic loading process.

Immediately after clicking:

  • The content is not yet available.

  • Selenium must wait for the text to appear before continuing execution.


Create the Custom Waiting Condition

lambda browser:
"Hello World!" in browser.find_element(
    By.CSS_SELECTOR,
    "#finish"
).text

This lambda function acts as the custom waiting condition.

It performs the following steps repeatedly:

  • Locates the #finish element.

  • Retrieves its text content.

  • Checks whether "Hello World!" is present.

  • Returns True if the condition is satisfied.

  • Returns False otherwise.

Unlike Selenium’s predefined Expected Conditions, Custom Waits allow you to define synchronization behavior that is specific to your application’s requirements.


Wait Until the Custom Condition is Satisfied

WebDriverWait(driver, 10).until(
    lambda browser:
    "Hello World!" in browser.find_element(
        By.CSS_SELECTOR,
        "#finish"
    ).text
)

Selenium repeatedly executes the custom condition until:

  • "Hello World!" appears, or

  • The 10-second timeout expires.

As soon as the condition becomes True, Selenium immediately continues execution.


Validate the Result

assert "Hello World!" in driver.find_element(
    By.CSS_SELECTOR,
    "#finish h4"
).text

Verifies that:

  • The dynamic content loaded successfully.

  • The custom waiting condition behaved as expected.

  • Selenium synchronized correctly with the webpage.


How Custom Waits Work

The following diagram illustrates the process.

        Create Custom Condition
                    │
                    ▼
            Create WebDriverWait
                    │
                    ▼
          Execute Custom Condition
                    │
                    ▼
              Condition True?
                 │        │
                Yes       No
                 │         │
                 ▼         ▼
            Continue   Check Again
                            │
                    Timeout Reached?
                       │         │
                      No        Yes
                       │          │
                       ▼          ▼
                Continue Waiting
                             Throw
                      TimeoutException

Practical Example

Suppose an e-commerce website displays a “Stock Updated Successfully” message after checking product availability.

Since Selenium provides no built-in Expected Condition for this particular message, a Custom Wait can repeatedly check whether the expected text appears before continuing execution.


Automation Testing Example

Consider an online banking application.

After submitting a money transfer:

  • The transaction is processed.

  • The account balance is updated.

  • A custom success message appears.

  • The Download Receipt button becomes available.

A Custom Wait can repeatedly check whether the status text changes to:

Transfer Successful

before proceeding with the remaining test steps.


Real-World Example

Custom Waits are commonly used in:

  • Banking applications

  • E-commerce websites

  • CRM systems

  • Healthcare portals

  • Government websites

  • Enterprise web applications

They are particularly useful when built-in Expected Conditions cannot handle application-specific behavior.


Advantages of Custom Waits

  • Highly flexible.

  • Handles application-specific scenarios.

  • Improves synchronization.

  • Reduces flaky tests.

  • Works with any custom condition.


Limitations

  • Requires additional coding.

  • Slightly more complex than built-in Expected Conditions.

  • Incorrect logic may cause unnecessary timeouts.

  • Can become difficult to maintain if overused.


Common Mistakes Beginners Make

Writing Complex Custom Functions

Keep Custom Waits simple and focused on a single condition.

Avoid combining multiple unrelated conditions inside one custom wait whenever possible.


Forgetting to Return True or False

The custom condition must return:

  • True when the condition is satisfied.

  • False otherwise.

Without this, WebDriverWait cannot determine whether it should continue waiting.


Creating a Custom Wait for an Existing Expected Condition

Many synchronization scenarios are already covered by Selenium’s built-in Expected Conditions.

Examples include:

  • Visibility

  • Clickability

  • Presence of elements

  • Alerts

  • Frames

Use a Custom Wait only when no suitable built-in condition exists.


Best Practices

  • Use built-in Expected Conditions whenever possible.

  • Create Custom Waits only for application-specific requirements.

  • Keep custom functions simple and readable.

  • Use reasonable timeout values (typically 5–15 seconds).

  • Test Custom Waits thoroughly to ensure they behave as expected.


Conclusion

Custom Waits provide the highest level of flexibility in Selenium synchronization. They allow you to create your own waiting conditions when Selenium’s built-in Expected Conditions are not sufficient. Although they require slightly more coding, Custom Waits are invaluable for automating complex, dynamic web applications with unique synchronization requirements.


Frequently Asked Questions (FAQs)

What is a Custom Wait in Selenium?

A Custom Wait is a user-defined waiting condition that repeatedly checks for a specific application requirement before continuing execution.

When should I use a Custom Wait?

Use a Custom Wait when Selenium’s built-in Expected Conditions cannot handle your application’s behavior.

Can Custom Waits use WebDriverWait?

Yes.

Custom Waits are typically implemented using WebDriverWait together with a custom function or lambda expression.

Should I always use Custom Waits?

No.

Use Selenium’s built-in Expected Conditions whenever possible. Create Custom Waits only when necessary.

Are Custom Waits used in real-world automation frameworks?

Yes.

They are commonly used for complex enterprise applications where unique synchronization requirements cannot be handled using standard Expected Conditions.


Key Takeaways

  • Custom Waits allow you to define your own waiting conditions.

  • They are implemented using WebDriverWait together with a custom function or lambda expression.

  • Selenium repeatedly checks the custom condition until it returns True.

  • Custom Waits are useful for application-specific synchronization.

  • Use built-in Expected Conditions whenever possible.

  • Custom Waits provide maximum flexibility for advanced Selenium automation.