0

i have a while loop, it's working all fine, i just want to make a small modification on the line Marks = driver.find_element_by_xpath("HERE")

i want to make it like this: if Marks is not showing then quit loop

while len(driver.find_elements_by_xpath("xxxxx']")) != 1:
    try:
        wait.until(EC.visibility_of_element_located((By.XPATH, "xxxxx']")))
        List = driver.find_element_by_xpath("yyyyyyy")
        List.click()
        print('done1')
        time.sleep(2)
        Marks = driver.find_element_by_xpath("HERE")
edit here
        time.sleep(2)
        Marks.click()
        time.sleep(5)
        print('done3')
        driver.get("qqqqqqq")
        driver.find_element_by_xpath('qqqqqqq').click()
        wait.until(EC.visibility_of_element_located((By.XPATH, "qqqqqqq")))
    except:
        pass
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352

2 Answers2

0

You can do it with try/except. If Marks is not on the webpage (Python can't find it by XPath) the script will raise an error.

try:
  Marks = driver.find_element_by_xpath("HERE")
except:
  quit()
Andrej
  • 2,743
  • 2
  • 11
  • 28
0

From your code block it is not that clear why you want to pass within except. This means that you are willingly catching any error although you are absolutely not prepared for it and we also you don’t do anything about it.

However, to quit loop when Marks is not showing up i.e. resulting into NoSuchElementException you can handle it now in the except block as follows:

while len(driver.find_elements_by_xpath("xxxxx']")) != 1:
    try:
        wait.until(EC.visibility_of_element_located((By.XPATH, "xxxxx']")))
        List = driver.find_element_by_xpath("yyyyyyy")
        List.click()
        print('done1')
        time.sleep(2)
        Marks = driver.find_element_by_xpath("HERE")
        time.sleep(2)
        Marks.click()
        time.sleep(5)
        print('done3')
        driver.get("qqqqqqq")
        driver.find_element_by_xpath('qqqqqqq').click()
        wait.until(EC.visibility_of_element_located((By.XPATH, "qqqqqqq")))
    except NoSuchElementException:
        break
    

Note : You have to add the following import:

from selenium.common.exceptions import NoSuchElementException

tl; dr

Why is “except: pass” a bad programming practice?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352