Selenium waitForElement

Posted on

Question :

Selenium waitForElement

How do I write the function for Selenium to wait for a table with just a class identifier in Python? I’m having a devil of a time learning to use Selenium’s Python webdriver functions.

Asked By: Breedly


Answer #1:

From the Selenium Documentation PDF :

import contextlib
import selenium.webdriver as webdriver
import as ui

with contextlib.closing(webdriver.Firefox()) as driver:
    wait = ui.WebDriverWait(driver,10)
    # Do not call `implicitly_wait` if using `WebDriverWait`.
    #     It magnifies the timeout.
    # driver.implicitly_wait(10)  

    wait.until(lambda driver: driver.title.lower().startswith('cheese!'))

    # This raises
    #     selenium.common.exceptions.TimeoutException: Message: None
    #     after 10 seconds
    wait.until(lambda driver: driver.find_element_by_id('someId'))
Answered By: unutbu

Answer #2:

Selenium 2’s Python bindings have a new support class called for doing all sorts of things like testing if an element is visible. It’s available here.

NOTE: the above file is in the trunk as of Oct 12, 2012, but not yet in the latest download which is still 2.25. For the time being until a new Selenium version is released, you can just save this file locally for now and include it in your imports like I’ve done below.

To make life a little simpler, you can combine some of these expected condition methods with the Selenium wait until logic to make some very handy functions similar to what was available in Selenium 1. For example, I put this into my base class called SeleniumTest which all of my Selenium test classes extend:

from selenium.common.exceptions import TimeoutException
from import By
import as EC
import as ui

def setUpClass(cls):
    cls.selenium = WebDriver()
    super(SeleniumTest, cls).setUpClass()

def tearDownClass(cls):
    super(SeleniumTest, cls).tearDownClass()

# return True if element is visible within 2 seconds, otherwise False
def is_visible(self, locator, timeout=2):
        ui.WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.CSS_SELECTOR, locator)))
        return True
    except TimeoutException:
        return False

# return True if element is not visible within 2 seconds, otherwise False
def is_not_visible(self, locator, timeout=2):
        ui.WebDriverWait(driver, timeout).until_not(EC.visibility_of_element_located((By.CSS_SELECTOR, locator)))
        return True
    except TimeoutException:
        return False

You can then use these easily in your tests like so:

def test_search_no_city_entered_then_city_selected(self):
    sel = self.selenium
    sel.get('%s%s' % (self.live_server_url, '/'))
Answered By: Dave Koo

Answer #3:

I have made good experiences using:

  • time.sleep(seconds)
  • webdriver.Firefox.implicitly_wait(seconds)

The first one is pretty obvious – just wait a few seconds for some stuff.

For all my Selenium Scripts the sleep() with a few seconds (range from 1 to 3) works when I run them on my laptop, but on my Server the time to wait has a wider range, so I use implicitly_wait() too. I usually use implicitly_wait(30), which is really enough.

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

Answered By: naeg

Answer #4:

I implemented the following for python for wait_for_condition since the python selenium driver does not support this function.

def wait_for_condition(c):
for x in range(1,10):
    print "Waiting for ajax: " + c
    x = browser.execute_script("return " + c)

to be used as

Wait that an ExtJS Ajax call is not pending:


A Javascript variable is set

wait_for_condition("CG.discovery != undefined;")


Answered By: Deven Kalra

Answer #5:

You could always use a short sleep in a loop and pass it your element id:

def wait_for_element(element):
     count = 1
              count = count + 1
         count = count + 1
         if(count > 300):
             print("Element %s not found" % element)
             #prevents infinite loop
Answered By: TheDawg

Answer #6:

Use Wait Until Page Contains Element with the proper XPath locator. For example, given the following HTML:

  <div id="myDiv">
    <table class="myTable">
      <!-- implementation -->

… you can enter the following keyword:

Wait Until Page Contains Element  //table[@class='myTable']  5 seconds

Unless I missed something, there is no need to create a new function for this.

Answered By: jro

Answer #7:

In case this helps …

In the Selenium IDE, I added …
Command: waitForElementPresent
Target: //table[@class=’pln’]

Then I did File>Export TestCase As Python2(Web Driver), and it gave me this …

def test_sel(self):
    driver = self.driver
    for i in range(60):
            if self.is_element_present(By.XPATH, "//table[@class='pln']"): break
        except: pass
    else:"time out")
Answered By: jcfollower

Answer #8:

easier solution:

    from import By    
    import time

    while len(driver.find_elements(By.ID, 'cs-paginate-next'))==0:
Answered By: Ben

Leave a Reply

Your email address will not be published.