1

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!

The Dan
  • 1,408
  • 6
  • 16
  • 41
  • 1
    See if the OR'ed XPATH works for you: `//button/div[contains(text(), "Anybody")] | //span/div[contains(text(), "Somebody")]`. –  Mar 15 '21 at 18:44
  • You could create a function that accepts either the entire function, or just the xpath string, with one try/except block and returns the value. Then you can put all of your xpath strings in a list, and do a lambda to run the list through the function. The basic concept can be seen here: https://stackoverflow.com/questions/13874666/how-to-write-multiple-try-statements-in-one-block-in-python – mr_mooo_cow Mar 15 '21 at 18:59
  • In this case you mention, will it wait 20 secs for any of the options, right? In case there is a match with both, what will happen? @JustinEzequiel – The Dan Mar 15 '21 at 19:00
  • You'll just have to try it yourself. –  Mar 15 '21 at 19:05
  • I'm wondering why you need to do this. If it's for testing this isn't a great approach, if it's for something else (scraping) you might want ot use a different technique: like the xpath OR... – DMart Mar 15 '21 at 19:22

1 Answers1

2

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 (available in selenium4) 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")]')))
    )
)
DMart
  • 2,401
  • 1
  • 14
  • 19