Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

python - Selenium Expected Conditions - possible to use 'or'?

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

from selenium.webdriver.support 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 (div.some_result) 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")) 
    or 
    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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:
            try:
                res = fn(driver)
                if res:
                    return True
                    # Or return res if you need the element found
            except:
                pass

Then call it like...

from selenium.webdriver.support import expected_conditions as EC
# ...
WebDriverWait(driver, 10).until( AnyEc(
    EC.presence_of_element_located(
         (By.CSS_SELECTOR, "div.some_result")),
    EC.presence_of_element_located(
         (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 NoSuchElementException 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...