QA teams should ensure that Selenium waits properly before going forward with actions like clicks or form submissions to simulate real user behavior. Even though Selenium Webdriver typically waits for the DOM to load before proceeding to the next step, extra waits are necessary in scenarios like:
- Dynamic or Ajax-loaded elements that appear after the initial page load.
- Elements present in the DOM but take time to be visible or interactable (e.g., a dropdown loading values after a user action).
To handle such scenarios, you can use Wait commands in Selenium. In this guide, learn what are Waits in Selenium, How to implement Selenium Wait for page to load and more.
Importance of Page Load in Selenium
A page load is the process of a web page being fetched from the server and fully rendered in the browser. This includes HTML, CSS, JavaScript, and all related resources like images and fonts. Here is why page load is important in Selenium:
- Page loads ensure the availability of elements before interaction, thus preventing test failures.
- It ensures synchronization between test steps and application behavior.
- Proper handling of page loads help spot performance issues like slow or incomplete page loads.
- It improves test reliability while working with dynamic or Ajax-loaded content.
- Reflects real user behavior
How to implement Selenium wait for page to load
Selenium Wait commands instruct a test to pause for a predetermined length of time before moving onto the next step in the script. The pause lets the page load and the web elements become visible/present/populated/clickable before WebDriver can interact with them and proceed with the test.
Wait commands are beneficial because Selenium will throw an Element Not Visible Exception if it cannot locate the element required for the test to run. With wait commands, the test will wait for the element to become available, thus preventing the exception from showing up.
Read More: Exception Handling in Selenium WebDriver
There are three ways to implement Selenium wait for page to load:
- Using Implicit Wait
- Using Explicit Wait
- Using Fluent Wait
Using Implicit Wait
The Implicit Wait tells WebDriver to wait a specific amount of time (say, 30 seconds) before proceeding with the next step. If the tester knows how much time the page and element will take to load, they should use Implicit Wait.
Let’s say a website under test takes ten seconds to load a page until a particular element shows up. In that case, set implicit wait for 10 seconds. The test will pause, and once the time passes, Webdriver will continue to run the script as planned.
WebDriver driver => new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://url_that_delays_loading"); WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
Note that the Implicit Wait function will be applicable as long as the current browser is open. That means all elements being searched for by the Selenium script will take the time laid out in the Implicit Wait.
Using Explicit Wait
The Explicit Wait is more advanced in its functioning. It instructs WebDriver to pause a test until a predetermined condition is fulfilled.
Let’s say the website under test has a feature displaying a pop-up. The user has to enter some data, following which a pop-up appears. This feature needs to be tested in this exact sequence, including the time taken for the user to input data, server response time, etc.
In this case, the Explicit Wait will wait for the pop-up to appear before proceeding with the test. However, since the test cannot wait an infinite amount of time, testers also insert a duration for WebDriver to pause before carrying on.
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Firefox() driver.get("http://www.example.com") #This is a dummy website URL try: elem = WebDriverWait(driver, 30).until( EC.presence_of_element_located((By.ID, "Element_to_be_found")) #This is a dummy element ) finally: driver.quit()
The code will instruct WebDriver to wait for 30 seconds. If the specified condition is met before that, the test will proceed, If not, it will wait the whole 30 seconds before moving forward.
In order to declare an explicit wait, one has to use “ExpectedConditions”. The following Expected Conditions in Selenium can be used in Explicit Wait:
- alertIsPresent()
- elementSelectionStateToBe()
- elementToBeClickable()
- elementToBeSelected()
- frameToBeAvaliableAndSwitchToIt()
- invisibilityOfTheElementLocated()
- invisibilityOfElementWithText()
- presenceOfAllElementsLocatedBy()
- presenceOfElementLocated()
- textToBePresentInElement()
- textToBePresentInElementLocated()
- textToBePresentInElementValue()
- titleIs()
- titleContains()
- visibilityOf()
- visibilityOfAllElements()
- visibilityOfAllElementsLocatedBy()
- visibilityOfElementLocated()
Using Fluent Wait
The Fluent Wait is an advancement on the Explicit Wait. Using it, testers can define a specific condition and the frequency for which WebDriver should check for the condition to appear in a particular length of time.
Let’s say the website under test includes some elements that load dynamically. The tester knows it takes a total of 5 seconds to load, not more. But it can become visible anytime between zero to five seconds.
In this case, Fluent Wait comes to the rescue. The tester can use it to instruct Selenium WebDriver to keep checking on the element at regular intervals.
//Declare and initialise a fluent wait FluentWait wait = new FluentWait(driver); //Specify the timout of the wait wait.withTimeout(5000, TimeUnit.MILLISECONDS); //Specify polling time wait.pollingEvery(250, TimeUnit.MILLISECONDS); //Specify what exceptions to ignore wait.ignoring(NoSuchElementException.class) //This is how we specify the condition to wait on. wait.until(ExpectedConditions.alertIsPresent());
Fluent Wait operates with two main parameters: timeout value and polling frequency. The code defines timeout value as 5 seconds and polling frequency as 0.25 seconds. That means WebDriver will wait no more than 5 seconds to verify the specified condition. If the condition occurs (the element populates) during 5 seconds, it will move on to the next step in the test script. If not, it will return “ElementNotVisibleException”.
Read More: How to start with Selenium Debugging
Handling Asynchronous Page Loads
Web applications can load content asynchronously using JavaScript or Ajax. This implies that parts of the page may proceed to load or update after the initial DOM load is done. Selenium WebDriver does not automatically wait for these asynchronous events, that could lead tests to fail if elements don’t fully load or are visible.
You can manage such cases by:
- Using Explicit Waits to wait for specific conditions (e.g., element visibility, clickability).
- Waiting for Ajax calls to be done by checking for indicators such as loading spinners or particular DOM changes.
- Avoiding the use of fixed delays (Thread.sleep()) as they are unreliable and can slow down tests.
QA teams should strategically leverage Wait commands to ensure the scripts interact with the page only when it’s actually ready.
Common Challenges with Page Load and Selenium
Here are the challenges of page load and Selenium and the corresponding solutions:
1. Interacting with elements before they load
Solution: Use Explicit Waits like visibilityOfElementLocated
2. Handling dynamic/Ajax content
Solution: Wait for specific conditions or DOM changes
3. Test failures because of inconsistent load times
Solution: Execute Fluent Waits with timeout and polling frequency
4. Overuse of Thread.sleep() resulting in slow, flaky tests
Solution: Replace with smart waits (Implicit or Explicit)
Conclusion
Using Selenium Wait for page to load is quite necessary for automated Selenium testing since it is a common occurrence in everyday internet users’ browsing journey. Selenium Wait commands are exceptionally effective in doing so, and implementing them is fairly uncomplicated, making Browser Automation seamless, as the examples above have demonstrated.
Selenium Waits help detect and debug issues that may occur due to variations in time lag. However, for the results of these commands to be 100% accurate all the time, they must be run on real browsers and devices.
BrowserStack’s cloud Selenium grid offers 3500+ real devices and browsers for automated testing. That means users can run tests on multiple real devices and browsers by simply signing up, logging in, and selecting the required combinations.
Run Selenium Tests on Real Browsers Free
Frequently Asked Questions
1. How to wait for 30 seconds in Selenium?
You can use Explicit wait to wait for 30 seconds in Selenium:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30)); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));
2. How to change the default timeout in Selenium
You can adjust the implicit wait to change the default timeout in Selenium
Global timeout for all element searches with implicit wait:
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
Here, you can customize the waiting time according to your test requirements.
Useful Resources for Selenium
Methods, Classes, and Commands
- Selenium Commands every Developer or Tester must know
- Selenium WebElement Commands
- Desired Capabilities in Selenium Webdriver
- Assert and Verify Methods in Selenium
- Understanding System setProperty in Selenium
- Select Class in Selenium : How to select a value in dropdown list?
- SendKeys in Selenium WebDriver
- getAttribute() method in Selenium: What, Why, and How to use
- How does Selenium isDisplayed() method work?
- findElement vs findElements in Selenium
- Types of Listeners in Selenium (with Code Examples)
- How to set Proxy in Firefox using Selenium WebDriver?
Configuration
- How to set up Selenium on Visual Studio
- How to configure Selenium in Eclipse
- Maven Dependency Management with Selenium
- How to Build and Execute Selenium Projects
XPath
- How to use XPath in Selenium?
- How to find element by XPath in Selenium with Example
- Top Chrome Extensions to find Xpath in Selenium
Locators and Selectors
- Locators in Selenium: A Detailed Guide
- CSS Selector in Selenium: Locate Elements with Examples
- How to Create Object Repository in Selenium
Waits in Selenium
- Wait Commands in Selenium C and C#
- Selenium Wait Commands: Implicit, Explicit, and Fluent Wait
- Understanding Selenium Timeouts
- Understanding ExpectedConditions in Selenium
- Understanding Role of Thread.sleep() in Selenium
Frameworks in Selenium
- Data Driven Framework in Selenium
- Implementing a Keyword Driven Framework for Selenium: A Practical Guide
- Hybrid Framework in Selenium
Miscellaneous
- How to create Selenium test cases
- How to set Proxy in Selenium?
- Difference between Selenium Standalone server and Selenium server
- Exception Handling in Selenium WebDriver
- How to use JavascriptExecutor in Selenium
- How to run your first Selenium test script
- Parallel Testing with Selenium
Best Practices, Tips and Tricks
- Top 5 Challenges Faced During Automation Selenium Testing
- 5 Selenium tricks to make your life easier
- 6 Things to avoid when writing Selenium Test Scripts
- Best Practices for Selenium Test Automation
- Why you should pay attention to flaky Selenium tests
- How to start with Selenium Debugging
- How to make your Selenium test cases run faster
- How to upgrade from Selenium 3 to Selenium 4
- Why you should move your testing to a Selenium Cloud?
Design Patterns in Selenium: Page Object Model and Page Factory
- Design Patterns in Selenium
- Page Object Model and Page Factory in Selenium
- Page Object Model and Page Factory in Selenium C#
- Page Object Model in Selenium and JavaScript
- Page Object Model and Page Factory in Selenium Python
Action Class
- How to handle Action class in Selenium
- How to perform Mouse Hover Action in Selenium
- Understanding Click Command in Selenium
- How to perform Double Click in Selenium?
- How to Drag and Drop in Selenium?
- How to Scroll Down or Up using Selenium Webdriver
- How To verify Tooltip Using Selenium
TestNG and Selenium
- Database Testing using Selenium and TestNG
- How to use DataProvider in Selenium and TestNG?
- All about TestNG Listeners in Selenium
- How to run parallel test cases in TestNG
- How to use TestNG Reporter Log in Selenium: Tutorial
- Prioritizing tests in TestNG with Selenium
JUnit and Selenium
- Understanding JUnit assertions for Selenium Testing with Examples
- How to run JUnit Parameterized Test in Selenium
- How to write JUnit test cases
- JUnit Testing Tutorial: JUnit in Java
- How to create JUnit Test Suite? (with Examples)
Use Cases
- Handling Login Popups in Selenium WebDriver and Java
- How to Launch Browser in Selenium
- How to handle Alerts and Popups in Selenium?
- How to get Selenium to wait for a page to load
- How to Find Element by Text in Selenium: Tutorial
- How to Read/Write Excel Data using Apache POI Selenium
- How to handle Captcha in Selenium
- How to handle multiple windows in Selenium?
- How to handle Multiple Tabs in Selenium
- How to find broken links in Selenium
- How to handle Cookies in Selenium WebDriver
- How to handle iFrame in Selenium
- How to handle Web Tables in Selenium
- How To Validate Text in PDF Files Using Selenium Automation
- Get Current URL in Selenium using Python: Tutorial
Types of Testing with Selenium
- Different Testing Levels supported by Selenium
- How to perform UI Testing with Selenium
- Regression Testing with Selenium: Tutorial
- UI Automation using Python and Selenium: Tutorial
- How to Run Visual Tests with Selenium: Tutorial
- How to perform ETL Automation using Selenium
- Cross Browser Testing in Selenium : Tutorial