More elegant way to write multiple try, except

I am looking for a better way to write a multiple condition try-except statement,

Actually I check for some condition “A” and if it fails, well I look for “B”,

In this case I am trying 2 different scenarios for selenium webdriver. Sometimes I try more than 2 options

    try:
        message_button = WebDriverWait(self.driver, 20).until(
            EC.element_to_be_clickable((By.XPATH, '//button/div[contains(text(), "Anybody")]')))
        return False
    except Exception as e:
        try:
            message_button = WebDriverWait(self.driver, 20).until(
                EC.element_to_be_clickable((By.XPATH, '//span/div[contains(text(), "Somebody")]')))
            return False
        except Exception as e:
            return "yes"

Also a way to look for both a at a time would be nice!

Answer

Couple of different things you do. you could OR in the xpath as noted above:

 message_button = WebDriverWait(self.driver, 20).until(
            EC.element_to_be_clickable((By.XPATH, '//button/div[contains(text(), "Anybody")] | //span/div[contains(text(), "Somebody")]')))

python does have any_of (in more recent versions) that behaves like a logical or:

WebDriverWait(browser, 10).until(
    EC.any_of(
            EC.element_to_be_clickable((By.XPATH, '//button/div[contains(text(), "Anybody")]')),
            EC.element_to_be_clickable((By.XPATH, '//span/div[contains(text(), "Somebody")]')))
    )
)

Leave a Reply

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