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).
CodePudding user response:
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")
CodePudding user response:
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]
This way I can use an if like this:
if alert:
generateButton.click()
img_wait = WebDriverWait(driver, timeout).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "image"))) #to avoid stale elements
else:
img = driver.find_elements(By.CLASS_NAME, "image")