TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Use Selenium WebDriver Waits in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python SeleniumPython Tutorials

Use Selenium WebDriver Waits in Python

Last updated: Sep 29, 2023 5:32 pm
By Meenakshi Agarwal
Share
10 Min Read
Selenium WebDriver Waits in Python Explained with Examples
SHARE

This tutorial will guide you through the concept of Selenium Webdriver waits (Implicit and Explicit Waits) and how to use them in Python.

Contents
Implicit WaitExplicit WaitHTML codeCode snippetStandard Expected Conditions

If you are doing automation in Selenium Python and wish to write error-free scripts, then you must learn to use waits. They let you handle any unexpected condition that may occur.

While automating a web application, you intend to write a script that can execute the following tasks.

Click here to Go Back to the main Selenium Python tutorial.

1. Load up the browser,
2. Open up the website,
3. Locate the elements, and
4. Execute the needed action.

However, the test script could sometimes fail due to the following reasons.

1. The web element was not present as it could not load due to runtime issues.
2. The usage of AJAX techniques in web applications has introduced uncertainty in the sense that the loading of the web page and the web elements present in it may happen at a different time span.
3. Many times, due to peak traffic or network latency, our application may behave differently than it does at normal, optimal conditions.

In these cases, we need to wait for the time to allow the web elements to load completely, before using them in our tests. Webdriver API provides two types of wait mechanisms to handle such conditions. We will discuss these wait conditions one by one in detail.

Selenium Webdriver Waits in Python

Selenium WebDriver Waits in Python Explained with Examples

The two types of Selenium Webdriver waits are :

  • Implicit Wait
  • Explicit Wait

Implicit Wait

An implicit wait directs the WebDriver to poll the DOM for a certain amount of time (as mentioned in the command) when trying to locate an element that is not visible immediately. The default value of time that can be set using Implicit wait is zero. Its unit is in seconds. Implicit wait remains associated with the web element until it gets destroyed.

Follow the below coding snippet illustrating the use of Implicit wait in Python.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.implicitly_wait(100)

driver.get("http://google.com")
driver.maximize_window()

print("Implicit Wait Example")

inputElement = driver.find_element_by_id("lst-ib")
inputElement.send_keys("Techbeamers")
inputElement.submit()

driver.close()

In the above code, the implicitly_wait( ) method tells the Webdriver to poll the DOM again and again for a certain amount of time. The timeout in this example is 100 seconds which will trigger if the target element is not available during that period.

We define Implicit wait for a Webdriver object so it will remain active until the existence of that object.

Explicit Wait

There may be scenarios when the wait time is uncertain. Explicit waits work as a savior there. Here we can define certain conditions, and Selenium WebDriver will proceed with the execution of the next step only after this condition gets fulfilled.

The explicit wait is the most preferred way of implementing Selenium webdriver waits in a test script. It provides the flexibility to wait for a custom condition to happen and then move to the next step.

Following are the two Selenium Python classes needed to implement explicit waits.

  • WebDriverWait, and
  • Expected Conditions class of the Python.

To understand its usage, let’s take an example of a Simple JavaScript alert on a webpage. A button is present on the web page to trigger that alert.

One of the use cases would be to click on the button and verify whether it fires the alert or not. Using the Explicit wait with Expected conditions WebDriver will wait for the time only till the Simple JavaScript is not visible on the screen. As soon as it appears, the WebDriver will move on to execute the next step.

However, if the alert does not appear until the maximum wait time defined in the explicit wait, Webdriver will throw a “NoAlertPresentException.”

HTML code

Here is the HTML code for generating a simple alert using JavaScript.

<body bgcolor="#C0C0C0">
<h1>Simple Alert Demonstration</h1>
<p>
Press button underneath to generate an alert.
</p>
<button onclick="alertFunction()" name ="alert">Generate Alert</button>
<script>
function alertFunction() {
    alert("Hello! I'm a Simple Alert.\nPlease press the 'OK' button.");
}
</script>
</body>
</html>

You need to save this file on your computer and name it the ‘Simple_Alert.HTML.’

Code snippet

Following is the code snippet demonstrating the Explicit wait.

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 cond
from selenium.common.exceptions import NoAlertPresentException
from selenium.common.exceptions import TimeoutException

driver = webdriver.Firefox()
driver.maximize_window()
#location = "file://<Specify Path to Simple_Alert.HTML>"
location = "file://C:/Users/Automation-Dev/Desktop/Meenakshi/Selenium%20Python/Simple_Alert.HTML"
driver.get(location)

#Press the "Alert" button to demonstrate the Simple Alert
button = driver.find_element_by_name('alert')
button.click()

try:
    # Wait as long as required, or maximum of 10 sec for alert to appear
    WebDriverWait(driver,10).until(cond.alert_is_present())

    #Change over the control to the Alert window
    obj = driver.switch_to.alert

    #Retrieve the message on the Alert window
    msg=obj.text
    print ("Alert shows following message: "+ msg )
    
    #Use the accept() method to accept the alert
    obj.accept()

except (NoAlertPresentException, TimeoutException) as py_ex:
    print("Alert not present")
    print (py_ex)
    print (py_ex.args)
finally:
    driver.quit()

In the above script, the timeout value is 10 seconds. It means the Webdriver will wait for 10 seconds before throwing a TimeoutException.
If the element is present, then it may return within 0 – 10 seconds. By default, the WebDriverWait API executes the ExpectedCondition every 500 milliseconds until it returns successfully.

If the ExpectedCondition matches, then the return value will be a Boolean (TRUE) whereas a non-null value for all other ExpectedCondition types.

Standard Expected Conditions

There are a number of standard conditions that you may commonly encounter while automating web pages. Below is the list displaying the names of each of them. All of these classes are available in the selenium.webdriver.support.expected_conditions Python module.

  1. class alert_is_present
    To wait for an alert to appear.
  2. class element_located_selection_state_to_be(ui_locator, is_selected)
    To wait for an element to locate having a specified state.
  3. class element_located_to_be_selected(ui_locator)
    To wait for an element to be located in the selected state.
  4. class element_selection_state_to_be(ui_element, is_selected)
    To wait to find an element having a specified state.
  5. class element_to_be_clickable(ui_locator)
    To wait for an element to locate which is in a clickable state.
  6. class element_to_be_selected(ui_element)
    To wait for an element to find which is in a selected state.
  7. class frame_to_be_available_and_switch_to_it(ui_locator)
    To wait for a frame to become available for the switchover.
  8. class invisibility_of_element_located(ui_locator)
    To wait for an element that is invisible or not in the DOM.
  9. class staleness_of(ui_element)
    To wait for an element to be removed from the DOM.
  10. class text_to_be_present_in_element(ui_locator, inner_text)
    To wait for an element to be found in a given text.
  11. class text_to_be_present_in_element_value(ui_locator, value)
    To wait for an element to be found with a given text inside the locator.
  12. class title_contains(title_text)
    To wait to find a title containing the specified text in a case-sensitive format.
  13. class title_is(title)
    To wait to find a title matching the exact specified text.
  14. class visibility_of(ui_element)
    To wait to find an element that is functionally visible.
  15. class visibility_of_all_elements_located(ui_locator)
    To wait to find all functionally visible elements the specified locator will return.
  16. class visibility_of_any_elements_located(ui_locator)
    To wait to find at least one functionally visible element the specified locator will return.
  17. class visibility_of_element_located(ui_locator)
    To wait to find a specific and functionally visible element the specified locator will return.

Quick Wrapup – Selenium Webdriver Waits in Python

In Selenium Python binding, you can easily find methods to handle these. It saves you from writing any user-defined expected condition class or creating a package for the same.

Understanding Selenium Webdriver waits is key to producing high-quality automation test scripts. We hope this tutorial has directed you to the right approach.

For more updates on Selenium Python tutorials, follow our social media accounts to notify you of more free and useful tutorials.

Best,

TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Locate Elements using Selenium Python How to Locate Elements using Selenium Python
Next Article Python for loop, syntax and examples Python For Loop Tutorial

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x