Spvda
Spvda

Reputation: 23

How define an conditional "if exist" element, with selenium?

When you load a page with a student, at least two options appear for you to click (if they studied high school, in the same house of studies). But this is not always the case. I want to condition the following:

wait = WebDriverWait(driver, 2)

if not wait.until(EC.element_to_be_clickable((By.XPATH, "//td[text()='AC']/following-sibling::td/input"))):
    print('Cargando reporte...')
    time.sleep(6)
    driver.save_screenshot(r'C:\Users\spvda\Desktop\{}.-image.png'.format(i))
    driver.quit()   
else:
    ait.until(EC.element_to_be_clickable((By.XPATH, "//td[text()='AC']/following-sibling::td/input"))).click()
    print('Cargando reporte...')
    time.sleep(6)
    driver.save_screenshot(r'C:\Users\spvda\Desktop\{}.-image.png'.format(i))
    driver.quit()

But, it don't work and get this: raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: (The message is empty).

How fix this?

Upvotes: 0

Views: 448

Answers (1)

cruisepandey
cruisepandey

Reputation: 29362

You can use find_elements to have a list and can check if the size > 0 then do some stuff othetrwise do something else.

try:
    if(len(driver.find_elements(By.XPATH, "//td[text()='AC']/following-sibling::td/input"))) > 0:
        print("When AC is visible in UI")
        wait.until(EC.element_to_be_clickable((By.XPATH, "//td[text()='AC']/following-sibling::td/input"))).click()
        print('Cargando reporte...')
        time.sleep(6)
        driver.save_screenshot(r'C:\Users\spvda\Desktop\{}.-image.png'.format(i))
        driver.quit()
    else:
        print('Cargando reporte...')
        time.sleep(6)
        driver.save_screenshot(r'C:\Users\spvda\Desktop\{}.-image.png'.format(i))
        driver.quit()
except:
    print("Something went wrong")
    pass

Upvotes: 2

Related Questions