artfulrobot artfulrobot - 1 year ago 127
Python Question

Selenium Expected Conditions - possible to use 'or'?

I'm using Selenium 2 / WebDriver with the Python API, as follows:

from import expected_conditions as EC

# code that causes an ajax query to be run

WebDriverWait(driver, 10).until( EC.presence_of_element_located( \
(By.CSS_SELECTOR, "div.some_result")));

I want to wait for either a result to be returned (
) or a "Not found" string. Is that possible? Kind of:

WebDriverWait(driver, 10).until( \
EC.presence_of_element_located( \
(By.CSS_SELECTOR, "div.some_result")) \
EC.presence_of_element_located( \
(By.CSS_SELECTOR, "div.no_result")) \

I realise I could do this with a CSS selector (
div.no_result, div.some_result
), but is there a way to do it using the Selenium expected conditions method?

Answer Source

I did it like this:

class AnyEc:
    """ Use with WebDriverWait to combine expected_conditions
        in an OR.
    def __init__(self, *args):
        self.ecs = args
    def __call__(self, driver):
        for fn in self.ecs:
                if fn(driver): return True

Then call it like...

from import expected_conditions as EC
# ...
WebDriverWait(driver, 10).until( AnyEc(
         (By.CSS_SELECTOR, "div.some_result")),
         (By.CSS_SELECTOR, "div.no_result")) ))

Obviously it would be trivial to also implement an AllEc class likewise.

Nb. the try: block is odd. I was confused because some ECs return true/false while others will throw exceptions for False. The Exceptions are caught by WebDriverWait so my AnyEc thing was producing odd results because the first one to throw an exception meant AnyEc didn't proceed to the next test.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download