Restarting all code when Selenium can't find element

Viewed 176

Sometimes my code does not work properly because there is no element, it gives an error and closes.

Instead of a search, I enter the things to be searched in order and pull the results accordingly.

Since the element I need to pull is not after the call, I get an error and it stops.

Since my project runs in the while loop, it needs to search for the things in the list that I have defined constantly, when there is no element, I have to start it from the beginning and make the next call from the while(True) loop.

I tried something like this for where the element doesn't exist, but I get an error and it's stopped:

    wait.until(EC.visibility_of_element_located((By.XPATH,"//*[@id='ShipResultId']/table/tbody/tr[2]/td[1]/div[1]/div/a"))).click()

    try:
        ucgen = wait.until(EC.visibility_of_element_located((By.XPATH,"//*[@id='body']/div[6]/div/div/div/div/div/div/div[2]/a/div/div/div[2]/div/img")))
        ucgen.click()
    except NoSuchElementException:
        driver.close()

I want to start from while(True) loop when this element is not present. So from the very beginning.

I did not share all the code so that it does not look crowded.

*

*

  • UPDATE

I found the solution:

    wait.until(EC.visibility_of_element_located((By.XPATH,"//*[@id='ShipResultId']/table/tbody/tr[2]/td[1]/div[1]/div/a"))).click()

    try:
        ucgen = wait.until(EC.visibility_of_element_located((By.XPATH,"//*[@id='body']/div[6]/div/div/div/div/div/div/div[2]/a/div/div/div[2]/div/img")))
        ucgen.click()
    except NoSuchElementException:
        driver.close()
        continue

Those who have the same problem should add:

driver.close()
continue
0 Answers
Related