Creating a try and except statement that will try multiple conditions

Question:

while True:
    try:
        element = driver.find_element(By.XPATH, "//*[contains(@href,'dawson')]")
        element.click()
        break
    except NoSuchElementException:
        driver.refresh()
        time.sleep(3)

Above is the try and except block that looks for a word in a Href and if it contains it the element is clicked. I wish to go through multiple of these given words and try them. So if the first word is not found it then goes on to the next word. It does not matter if it refreshes in between I just want it to iterate through these words and if it finds one it will click. How can I add more words into the try block?

Any help would be great.

Thank you

Asked By: John Stepehns

||

Answers:

Search for an element in separate loop

def find_link_by_word_in_href(driver, words):
    for word in words:
        try:
            return driver.find_element(By.XPATH, f"//*[contains(@href,'{word}')]")
        except NoSuchElementException:
            pass

while True:
    element = find_link_by_word_in_href(driver, ['dawson', 'denbigh', 'and_so_on'])
    if element is not None:
        element.click()
        break
    else:
        driver.refresh()
        time.sleep(3)
Answered By: Ivan Reshetnikov

To catch multiple types of exceptions in Python, you can specify them in a tuple after the except keyword. Here is how you can modify your code to also catch OSError:

try:
    full_dict = xmltodict.parse(open(filepath_or_xml, 'rb'))
except (FileNotFoundError, OSError):
    full_dict = xmltodict.parse(filepath_or_xml)

Answered By: Talha Ilyas