In python is possible to create an infinite loop for searching an element in a page?

Viewed 125

I'm trying to create an loop for searching a xpath in a page until is available.

I'm trying with this:

cart = driver.find_element_by_xpath('//*[@id="add-to-cart-button"]')
if not cart:
    webdriver.ActionChains(driver).send_keys(Keys.F5).perform()
else:    
    driver.find_element_by_xpath('//*[@id="add-to-cart-button"]').click()

But is impossible to define cart because the xpath is not yet available.

How you do it?

1 Answers

Wrap the click() within a try/catch{} block as follows:

while True:
    try:
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='add-to-cart-button']"))).click()
        break
    except TimeoutException:
        driver.ActionChains(driver).send_keys(Keys.F5).perform()
        

Note: You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
Related