Home > Blockchain >  exit python script when no match in for loop
exit python script when no match in for loop

Time:12-21

With selenium in python i want to click on a html div container if it contains some words and if it can't find any the script must exit. With the below code it is working if there is a div containing a word from the text list but how do i exit where non of the words is found? With the code below it executes order.click because this is outside the for loop. I only want to execute order.click() and go further with the rest of the script break if words are found

    text = ["Dog", "Cat", "Bird"]

    for word in text:
        try:
            order = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//div/p[contains(text(),'{}')]".format(word))))
            if order != None:
                print(f"found div with word: {word}")
                break
        except:
            print(f"did NOT found div with word: {word}")

    order.click()
 
  # and more commands after this....

CodePudding user response:

import sys

And in the except:

    text = ["Dog", "Cat", "Bird"]
    is_found = False
    for word in text:
        try:
            order = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//div/p[contains(text(),'{}')]".format(word))))
            if order != None:
                print(f"found div with word: {word}")
                is_found = True
                break
        except:
            print(f"did NOT found div with word: {word}")

    if is_found == False:
        sys.exit()
    order.click()
 
  # and more commands after this....

This is if you want to exit the whole script.

If you just want to not run order.click(), Then move this line in your try scope:

try:
            order = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//div/p[contains(text(),'{}')]".format(word))))
            if order != None:
                print(f"found div with word: {word}")
                order.click()
                break

CodePudding user response:

I think you need to include the "order.click()" in the indented part of the code that check if the item is found in the list, like below.

text = ["Dog", "Cat", "Bird"]

for word in text:
    try:
        order = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.XPATH, "//div/p[contains(text(),'{}')]".format(word))))
        if order != None:
            print(f"found div with word: {word}")
            order.click()
            break
    except:
        print(f"did NOT found div with word: {word}")
  • Related