Selenium – Wait For Element – Python

By | 14/06/2015

In Test Automation progress, one og the most important point is check element existence status. Sometimes you need to wait for any element to be appear or disappear. Selenium has wait and Expected Conditions functions.

following examples is a simple action that wait for a <div> element with ID of “ajaxReturnDiv”.

# -*- coding: UTF-8 -*-
import unittest
import time
import datetime
from selenium import webdriver
from import By
from import WebDriverWait
from import expected_conditions as EC

class TestClass(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()
    def test_MahsumAkbasNet_Wait_Element(self):
        wait = WebDriverWait(self.driver, 30)
        wait.until(EC.visibility_of_element_located((By.ID, "ajaxReturnDiv")))

    def tearDown(self):

if __name__ == '__main__':

after click on button, an ajax request is triggering and then(wait about 6 seconds) a div is present on the page. following html code is displayed

<div id=”ajaxReturnDiv”>It is ajax response text</div>

output is:

Ran 1 test in 22.437s


what happen if element not become exist! ? change name  of element like following and run your code:

wait.until(EC.visibility_of_element_located((By.ID, "fooDiv")))

ERROR: test_MahsumAkbasNet_Wait_Element (__main__.TestClass)
Traceback (most recent call last):
File “D:\xxx\src\unittestpackage\Copy of”, line 24, in test_MahsumAkbasNet_Wait_Element
wait.until(EC.visibility_of_element_located((By.ID, “fooDiv”)))
File “C:\Python27\lib\site-packages\selenium\webdriver\support\”, line 75, in until
raise TimeoutException(message, screen, stacktrace)
TimeoutException: Message:
at FirefoxDriver.prototype.findElementInternal_ (file:///d:/users/makbas/appdata/local/temp/tmp4htces/extensions/
at FirefoxDriver.prototype.findElement (file:///d:/users/makbas/appdata/local/temp/tmp4htces/extensions/
at DelayedCommand.prototype.executeInternal_/h (file:///d:/users/makbas/appdata/local/temp/tmp4htces/extensions/
at DelayedCommand.prototype.executeInternal_ (file:///d:/users/makbas/appdata/local/temp/tmp4htces/extensions/
at DelayedCommand.prototype.execute/< (file:///d:/users/makbas/appdata/local/temp/tmp4htces/extensions/

Ran 1 test in 42.534s

FAILED (errors=1)

it is Failed because couldn’t find element.
in this post, i show visibility_of_element_located() function, and stay tuned for next post to show all function !!!

Leave a Reply

Your email address will not be published. Required fields are marked *