Home > OS >  Creating a try and except statement that will try multiple conditions
Creating a try and except statement that will try multiple conditions

Time:07-16

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

CodePudding user response:

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)
  • Related