1

I'm using Python Selenium to fill a form. When I click a button like this:

Button = driver.find_element(By.XPATH, '//*[@id="root"]/div[1]/form/button')
Button.click()
img_wait = WebDriverWait(driver, timeout).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "image")))
img = driver.find_elements(By.CLASS_NAME, "image")

What happens is that sometimes the website doesn't process the request correctly and opens up a modal with an error message (CLASS_NAME "alert").

What I would like to do is, while waiting for the class "image" to load, if any element with class "alert" gets loaded by the page, hit the button again. Otherwise just keep waiting (I have a timeout exception anyway at the end).

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

2 Answers2

0

Incase the website doesn't process the request correctly and opens up the modal with an error message (CLASS_NAME "alert") to click on the button again you can wrap up the search for the alert within a try-except{} block as follows:

Button = driver.find_element(By.XPATH, '//*[@id="root"]/div[1]/form/button')
Button.click()
try:
    WebDriverWait(driver, timeout).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "alert")))
    print("Alert was found")
    driver.find_element(By.XPATH, '//*[@id="root"]/div[1]/form/button')
except TimeoutException:
    print("Alert wasn't found")
img_wait = WebDriverWait(driver, timeout).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "image")))
img = driver.find_elements(By.CLASS_NAME, "image")
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Thanks, this is a working solution but it would slow down the process a lot. If the code is inside a for loop, waiting for the timeout exception for every iteration would make it extremely inefficient. Is there a way to detect the element "alert" while it is waiting for the element "image"? – Francesco Calderone Aug 03 '22 at 09:46
  • I don't see any issue with the code being _inside a for loop_. However the `timeout` should be configurable. – undetected Selenium Aug 03 '22 at 10:16
0

I've actually found a solution:

img_wait = WebDriverWait(driver, timeout).until(lambda x: x.find_elements(By.CLASS_NAME, "image") or x.find_elements(By.CLASS_NAME, "alert"))[0]
alert = driver.find_elements(By.CLASS_NAME, "alert")

This way I can use an if like this:

if alert:
    print("alert found")
    Button.click()
    img_wait = WebDriverWait(driver, timeout).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "image")))
    image = driver.find_elements(By.CLASS_NAME, "image")
else:
    image = driver.find_elements(By.CLASS_NAME, "image")

which prevents stale elements as well