0

I'm writing something in selenium to automate a courseware my school made, I have this infinite loop that goes through the pages of a page and answers the questions until its done, but when I try this I get "No element" then the whole program stops, I've tried try/except NoSuchElementException but there's no option to retry the loop after that.

while True:
    try:
        clickable = driver.find_element(by=By.XPATH, value='/html/body/div[1]/div[1]/header/div/nav/button[3]/span').click() # arrows to go to next page
        time.sleep(.3)
        clickable = driver.find_element(by=By.XPATH, value='/html/body/div[2]/div[3]/div[3]/div[3]/div[2]/div[5]/button[3]').click() # show answers button
        time.sleep(.3)
        clickable = driver.find_element(by=By.XPATH, value='/html/body/div[1]/div[3]/div/button').click() # orange slides arrow
        time.sleep(.3)
    except NoSuchElementException:
        # need to retry loop somehow

Tried to retry a loop, expected it to retry.

Prophet
  • 32,350
  • 22
  • 54
  • 79
  • Does this answer your question? [Selenium - wait until element is present, visible and interactable](https://stackoverflow.com/questions/59130200/selenium-wait-until-element-is-present-visible-and-interactable) – tbhaxor Nov 12 '22 at 23:07

1 Answers1

0

You can do it by moving to a separate function the part that goes after opening next page. This gives you a possibility to call it whenever you want:

def handle_answers(driver):
    clickable = driver.find_element(by=By.XPATH, value='/html/body/div[2]/div[3]/div[3]/div[3]/div[2]/div[5]/button[3]').click()  # show answers button
    time.sleep(.3)
    clickable = driver.find_element(by=By.XPATH, value='/html/body/div[1]/div[3]/div/button').click()  # orange slides arrow
    time.sleep(.3)

while True:
    clickable = driver.find_element(by=By.XPATH, value='/html/body/div[1]/div[1]/header/div/nav/button[3]/span').click()  # arrows to go to next page
    time.sleep(.3)
    try:
        handle_answers(driver)
    except NoSuchElementException:
        handle_answers()

You can even try until success:

def handle_answers(driver):
    clickable = driver.find_element(by=By.XPATH, value='/html/body/div[2]/div[3]/div[3]/div[3]/div[2]/div[5]/button[3]').click()  # show answers button
    time.sleep(.3)
    clickable = driver.find_element(by=By.XPATH, value='/html/body/div[1]/div[3]/div/button').click()  # orange slides arrow
    time.sleep(.3)
    return True

while True:
    clickable = driver.find_element(by=By.XPATH, value='/html/body/div[1]/div[1]/header/div/nav/button[3]/span').click()  # arrows to go to next page
    time.sleep(.3)
    stop = False
    while not stop:
        try:
            stop = handle_answers(driver)
        except NoSuchElementException:
            continue
Eugeny Okulik
  • 1,331
  • 1
  • 5
  • 16