Selenium WebDriver provides two types of waits - implicit wait and explicit wait. The main difference between them lies in the fact that implicit wait applies to the entire session while explicit wait applies only to specific instances.
- Implicit Wait:
Implicit Wait is applied globally and will be available for the entire WebDriver instance. Once set, it will wait for the element before throwing a "NoSuchElementException". The default value is 0.
Here is an example in Python:
from selenium import webdriver
driver = webdriver.Firefox()
driver.implicitly_wait(10) # seconds
driver.get("http://somedomain/url_that_delays_loading")
myDynamicElement = driver.find_element_by_id("myDynamicElement")
In JavaScript:
const {Builder, By, Key, until} = require('selenium-webdriver');
let driver = new Builder().forBrowser('firefox').build();
driver.manage().setTimeouts( { implicit: 10000 } );
driver.get('http://somedomain/url_that_delays_loading');
let myDynamicElement = driver.findElement(By.id('myDynamicElement'));
- Explicit Wait:
Explicit Wait is code you define to wait for a certain condition to occur before proceeding further. It is an intelligent kind of wait, but it can be applied only for specified elements. Explicit wait is more extendible in terms of functionality compared to an implicit wait as it allows you to set up more complex and customized conditions before proceeding further in the code.
Here is an example in Python:
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://somedomain/url_that_delays_loading")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
finally:
driver.quit()
In JavaScript:
const {Builder, By, Key, until} = require('selenium-webdriver');
let driver = new Builder().forBrowser('firefox').build();
driver.get('http://somedomain/url_that_delays_loading');
driver.wait(until.elementLocated(By.id('myDynamicElement')), 10000);
Remember, these waits are telling WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements. They will not make WebDriver wait if it can find the element immediately.